<?php

namespace User\Controller;

use Common\Controller\AdminbaseController;
use Common\Lib\Getui\GetuiTrait;
use Think\Model;
use User\Model\Amount;
use User\Model\RoleUser;
use User\Model\WareHouse;

class ExamineController extends AdminbaseController
{
    use GetuiTrait;
    private $model;
    private $user_model;
    private $sub_model;
    private $renewal_model;
    private $jum_url;

    public function __construct()
    {
        parent::__construct();
        $this->model = M( "ders a", 'or', C( 'DB_CONFIG2' ) );
        $this->sub_model = M( "sub", 'orders_', C( 'DB_CONFIG2' ) );
        $this->user_model = M( "user", 'system_', C( 'DB_CONFIG2' ) );
        $this->renewal_model = M( "renewal", 'orders_', C( 'DB_CONFIG2' ) );
        $this->jum_url = 'http://127.0.0.1/';
    }


    /** 审核列表页面（初次审核、续借审核列表）
     * @param int    $type     [order表里面的status状态]
     * @param string $is_renew [对应order表里面的renew状态，表示是否是续借]
     * @param bool   $byuser   [是否是认领客户 0不是 1是]
     *                         续借未审核列表：$this->index( '0', '1', false );
     * @param int    $type  [order表里面的status状态]
     * @param string $is_renew  [对应order表里面的renew状态，表示是否是续借]
     * @param bool   $byuser
     * @param bool   $xj_display_type 续借状态区分 -1 全部 0待激活 1正常+已激活
     * 续借未审核列表：$this->index( '0', '1', false );
     */
    public function index($type = 0, $is_renew = '0', $byuser = true,$xj_display_type=-1)
    {
        $isChuWeiList = false;
        0 === $type && '0' === $is_renew && true === $byuser && -1 === $xj_display_type && ($isChuWeiList=true);//判断是否是初次未审核列表
        $isShenhebutonggluoList = false;
        '6,9' === $type && $is_renew === '0,1' && true === $byuser && -1 === $xj_display_type && ($isShenhebutonggluoList=true);//判断是否是审核不通过列表
        $isDaifangkuangList = false;
        10 === $type && $is_renew === '0,1' && false === $byuser && -1 === $xj_display_type && ($isDaifangkuangList=true);//判断是否是待放款列表
        $isChuFangkuangList = false;
        ($type === '8' ||  $type === '1,8') && '0' === $is_renew && true === $byuser && -1 === $xj_display_type && ($isChuFangkuangList=true);//判断是否是初次已放款列表
        $isXuWeiList = false;
        '0' === $type && '1' === $is_renew && false === $byuser && 1 === $xj_display_type &&($isXuWeiList=true);//判断是否是续借未审核列表
        $isXuWeiWeiJi = false;
        '0' === $type && '1' === $is_renew && false === $byuser && 0=== $xj_display_type &&($isXuWeiWeiJi=true);//判断是否是续借未审核未激活列表
        $isXuFangList = false;
        '8' === $type && '1' === $is_renew && false === $byuser && $xj_display_type=-1 && ($isXuFangList=true);//判断是否是续借已放款列表

        $isNeedTotal = false;
        if($isChuWeiList || $isShenhebutonggluoList || $isDaifangkuangList || $isChuFangkuangList || $isXuWeiList || $isXuWeiWeiJi || $isXuFangList){//判断是否要查合计
            $isNeedTotal = true;
        }

        $where = [];
        if($type==10){//如果是待放款，增加一个必须条件
            $where[] = 'a.overdue_m_status=0';//必须垫审通过才行
        }
        if($type==8 || $type=='1,8'){
            if(!$is_renew){
                $beta_type=I('request.types',0);
                if($beta_type==99){
                    $type='3';
                }else{
                    if($beta_type==1){
                        $beta_type='1,8';
                    }
                    if($beta_type==10){
                        $beta_type='1,2,3,4,8';
                    }
                    $type=$beta_type;
                    $t=date('Y-m-01');
                    $where[]='a.loan_time>="'.$t.'"';
                    $t=date('Y-m-d', strtotime("$t +1 month -1 day"));
                    $where[]='a.loan_time<="'.$t.'"';
                }
                $where[] = 'a.lastuser_id not in (19,21)';
            }
        }
//        $beta_type=I('request.types',0);
//        if(!empty($beta_type)){
//            $type=$beta_type;
//            if($beta_type==99){
//                $type='1,2,3,4,8';
//                $where[] = 'a.lastuser_id not in (19,21)';
//            }
//        }
        //续借状态  -1表示全部
        if($xj_display_type!=-1){
            if($xj_display_type==0){
                $where[] = 'a.is_display=0';
            }else{
                $where[] = '(a.is_display=1 OR a.is_display=2)';
            }
        }else{
            $where[] = '(a.is_display=1 OR a.is_display=2)';
        }

        if($byuser) {
            $byuser = I( 'request.byusers', 0 );
            //当前管理员ID是否为1，判断是否是管理员吧
            if(get_current_admin_id() == 1 && $byuser == 0) {
                $byuser = 3;
            }
            $group = get_groups_admin_user();
            //3表示审核专员，8表示风控经理
            if($group == 3 || $group == 8) {
                if(get_current_admin_id()==198 && $type==3){//指定风控不在规则内
                    //$byuser = 2;
                }else{
                    $byuser = 2;
                }
            }
            switch($byuser) {
                case '1':
                    $where[] = 'byusers=0';
                    break;
                case '3':
                    break;
                default:
                    if($type=='6,9'){
                        if(I('request.byusers')=='1'){
                            $where[] = '(byusers = '.get_current_admin_id().' OR byusers = 0)';
                        }else if(I('request.byusers')=='2'){
                            $where[] = 'byusers =' . get_current_admin_id();
                        }
                    }else{
                        if('3'==I('request.byusers')){
                            $where[] = '(byusers = '.get_current_admin_id().' OR byusers = 0)';
                        }elseif('1'==I('request.byusers')){
                            $where[] = 'byusers=0';
                        }else{
                            $where[] = 'byusers =' . get_current_admin_id();
                        }
                    }
            }
        }
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts', 0 )) {
            if($type == 0) {
                $str = 'a.crtime';
            } else if($type == '6,9') {
                $str = 'a.crtime';
            } else {
                $str = 'a.loan_time';
            }
            $where[] = $str . ' >= "' . date( 'Y-m-d 00:00:00', strtotime( $name ) ) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            if($type == 0) {
                $str = 'a.crtime';
            } else if($type == '6,9') {
                $str = 'a.crtime';
            } else {
                $str = 'a.loan_time';
            }
            $where[] = $str . ' <= "' . date( 'Y-m-d 23:59:59', strtotime( $name ) ) . '"';
        }
        //修改时间
        if($name = I( 'request.starts_mod', 0 )) {
            $where[] = 'a.modtime >= "' . date( 'Y-m-d 00:00:00', strtotime( $name ) ) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] =   'a.modtime <= "' . date( 'Y-m-d 23:59:59', strtotime( $name ) ) . '"';
        }
        if($name = I( 'request.caiwu', 0 )) {
            $where[] = 'a.loan_user like "%'.$name.'%"';
        }
        //客户类型 -1全部 0未知 1成人 2学生
        $is_adult = I( 'request.is_adult', -1 );
        if($is_adult!=-1) {
            $where[] = 'b.is_adult = '.$is_adult;
        }
        //手机类型 -1全部 0安卓 1苹果
        $photo_type = I( 'request.photo_type', -1 );
        if(-1!=$photo_type) {
            $where[] = 'b.photo_type = '.$photo_type;
        }
        //初次 续借
        $renew = I( 'request.renew', 0 );
        if(!empty($renew)) {
            $renew-=1;
            $is_renew=$renew;
        }
        //电审
        $m_status = I( 'request.overdue_m_status', 0 );
        if(!empty($m_status)) {
            $m_status-=1;
            if($m_status==0){
                $where[] = 'a.overdue_m_status is null ';
            }else{
                $where[] = 'a.overdue_m_status = 0';
            }
        }
        if($isXuWeiList && ($name = I('request.top_2_loan_user'))){//续借待审列表接收上次放款人条件
            $where[] = 'c.top_2_loan_user like "'.$name.'%"';
        }
        $shenhe = I( 'request.fengkong', 0 );
        if(!empty( $shenhe )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $shenhe . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers =0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers in (' . implode( ',', $i ) . ')';
                $where[] = 'a.lastuser_id not in (19,21)';
                //$type = '1,2,3,4,8';
            }
        }
        $shenhe = I( 'request.shenhe', 0 );
        if(!empty( $shenhe )) {
            $where[] = 'a.lastuser_name like "%' . $shenhe . '%"';
        }
        //快速审核
        $fast_auditing = I( 'request.fast_auditing', 0 );
        if(!empty( $fast_auditing ) && is_numeric($fast_auditing)) {
            $fast_auditing-=1;
            $where[] = 'a.fast_auditing =' . $fast_auditing ;
        }
        $order='';
        if($type==0){
            $order='b.modtime desc,';
        }
        $where[] = "a.status in (" . $type . ") and  a.renew in ({$is_renew}) ";//限制状态
        if($isXuWeiList){
            $sql = "SELECT COUNT(DISTINCT b.id) AS _count FROM orders a 
                        LEFT JOIN `system_user` b ON a.user_id=b.id  
                        LEFT JOIN 
                        (
                            SELECT ma.user_id,oa.loan_user AS top_2_loan_user FROM 
                            (
                                SELECT 
                                user_id,
                                LEFT(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''),LENGTH(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''))-1) AS top_2_oid
                                FROM orders 
                                GROUP BY user_id
                            ) ma
                            LEFT JOIN orders oa ON ma.top_2_oid=oa.id
                        ) c ON c.user_id=a.user_id
                        WHERE ( ".implode( ' and ', $where )."  ) LIMIT 1";
            $for_count = $this->model->query($sql);
            $count = $for_count[0]['_count'];
        }else{
            $count = M( "user b", 'system_', C( 'DB_CONFIG2' ) )->join( "left JOIN orders a on a.user_id=b.id and a.renew in ({$is_renew})" )->where( $where )->count();
        }
        $page = $this->page( $count, 20 );
        if($isNeedTotal === true){
            $fields = 'sum(a.amount) as total_amount';
            //如果是初次已放款列表，需要再统计有一项》已放款本金
            if($isChuFangkuangList){
                $fields .= ',sum(a.amount-a.interest-a.examine-a.consulting-10) as fk_total';
            }
            //如果是续借未审核列表，where条件会加上上次放款人的搜索条件，必须要影响到合计
            if($isXuWeiList){
                $sql = "SELECT ".$fields." FROM orders a 
                        LEFT JOIN `system_user` b ON a.user_id=b.id  
                        LEFT JOIN 
                        (
                            SELECT ma.user_id,oa.loan_user AS top_2_loan_user FROM 
                            (
                                SELECT 
                                user_id,
                                LEFT(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''),LENGTH(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''))-1) AS top_2_oid
                                FROM orders 
                                GROUP BY user_id
                            ) ma
                            LEFT JOIN orders oa ON ma.top_2_oid=oa.id
                        ) c ON c.user_id=a.user_id
                        WHERE ( ".implode( ' and ', $where )."  ) LIMIT 1";
                $for_total = $this->model->query($sql);
                $for_total = reset($for_total);//取第一个
            }else{
                $for_total = $this->model
                    ->join( "LEFT JOIN system_user b on a.user_id=b.id " )
                    ->where( implode( ' and ', $where ) )
                    ->field( $fields )
                    ->find();
            }
            $this->assign($for_total);
        }
        //如果是续借未审核列表，要加上次放款人字段
        $fields_search = 'a.fast_auditing,a.user_id,a.is_display,b.name,b.mobile,b.account_status,b.byusers,b.identity,b.photo_type,b.education,b.code,a.id,a.order_id,a.status,a.amount,a.crtime,a.stages,a.lastuser_name,a.loan_time,a.loan_day,a.loan_user,a.interest,a.examine,a.consulting,b.is_adult,b.photo_type';
        $orderBy = $order."a.loan_time DESC,a.crtime DESC,a.id desc";
        if($isXuWeiList){
            $fields_search .= ',c.top_2_loan_user';
            $sql = "SELECT ".$fields_search." FROM orders a 
                    LEFT JOIN `system_user` b ON a.user_id=b.id   
                    LEFT JOIN 
                    (
                        SELECT ma.user_id,oa.loan_user AS top_2_loan_user FROM 
                        (
                        SELECT 
                        user_id,
                        LEFT(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''),LENGTH(REPLACE(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id),',',-2),',',-1),''))-1) AS top_2_oid
                        FROM orders 
                        GROUP BY user_id
                        ) ma
                        LEFT JOIN orders oa ON ma.top_2_oid=oa.id
                    ) c ON c.user_id=a.user_id
                    WHERE ( ".implode( ' and ', $where )."  ) 
                    ORDER BY ".$orderBy." LIMIT ".$page->firstRow . ',' . $page->listRows;
            $list = $this->model->query($sql);
        }else{
            $list = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id " )
                ->where( implode( ' and ', $where ) )
                ->order( $orderBy )
                ->limit( $page->firstRow . ',' . $page->listRows )
                ->field( $fields_search )
                ->select();
        }
        $ids = [];
        $overdue_id=[];
        foreach($list as $v) {
            $overdue_id[]=$v['id'];
            if(empty( $v['byusers'] )) {
                continue;
            }
            $ids[$v['byusers']] = $v['byusers'];
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        //查逾期客户
//        if(!empty($overdue_id)){
//            $overdueUsers = M( 'log', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'types' => 5,'status'=>1 ] )
//                ->where('user_id in ('.implode(',',$overdue_id).')')->group( 'user_id' )->getField( 'user_id,types' );
//            $this->assign( 'overdueUsers', $overdueUsers );
//        }
        $codes = [];
        foreach($list as $v) {
        	if(!empty( $v['code'] )) {
        		$codes[$v['code']] = '"'.$v['code'].'"';
        	}
        }

        if(!empty( $codes )) {
        	$c = [];
        	$co = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->field( 'code,name' )->select();
        	foreach($co as $v) {
        		$c[$v['code']] = $v['name'];
        	}
        	$this->assign( 'codes', $c );
        }
        if(!empty($overdue_id)){//查询是否逾期
            $overdueUsers=M( "renewal", 'orders_', C( 'DB_CONFIG2' ) )
                ->where('oid in ('.implode(',',$overdue_id).') and status=1')->group('oid')->getField( 'oid,id' );
            $this->assign( 'overdueUsers', $overdueUsers );
            if($type==8){
                $pay=M( "pay", 'order_', C( 'DB_CONFIG2' ) )
                    ->where('oid in ('.implode(',',$overdue_id).')')->field('oid,ret,status')->select();
                $pays=[];
                foreach($pay as $v){
                    $pays[$v['oid']]=$v;
                }
                $this->assign( 'pays', $pays );
            }
        }
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 续借-正常+已激活
     */
    public function cntinued()
    {
        $this->index( '0', '1', false, 1 );
    }

    /*
     * 续借-未激活
     */
    public function cntinued_zcyjh()
    {
        $this->index( '0', '1', false,0 );
    }

    /*
     * 审核不通过
     */
    public function indexs()
    {
        $this->index( '6,9', '0,1' );
    }

    /*
     * 待放款
     */
    public function loan_last()
    {
        $this->index( 10, '0,1', false );
    }

    /*
     * 已放款
     */
    public function loan()
    {
        $group = get_groups_admin_user();
        if($group == 3 || $group == 8) {
            $this->index( '8' );
        } else {
            $this->index( '1,8' );
        }
    }

    /*
     * 续借已放款列表
     */
    public function cntinued_loan()
    {
        $this->index( '8', '1', false );
    }

    public function info()
    {
        $id = I( 'get.id', 0 );
        if($id) {
            $type = I( 'get.type', 0 );
            $result = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( [ "a.id" => $id ] )
                ->field( 'b.account_status,b.name,b.mobile,a.*' )->find();
            //log
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $result['id'] . ' and types<8 and types>0' )->order( 'crtime desc' )->select();
            $logs = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $result['user_id'] . ' and  types=2' )->order( 'crtime desc' )->select();

            $ids = [];
            foreach($log as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            foreach($logs as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            if(!empty( $ids )) {
                $users = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                $user = [];
                foreach($users as $v) {
                    $user[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $user );
            }

            //来源表头
            $from_type = I('get.from_type');
            switch ($from_type){
                case '1':
                    $from_url = U('Examine/cntinued');
                    $from_text = '续借未审核';
                    $to_form_url = '';
                    break;
                case '2':
                    $from_url = U('Examine/cntinued_zcyjh');
                    $from_text = '续借未审核-未激活';
                    $to_form_url = '';
                    break;
                case '3':
                    $from_url = U('Padtrial/index');
                    $from_text = '电审未审核列表';
                    $to_form_url = U('Padtrial/padtrial',['id'=>$id]);
                    break;
                case '4':
                    $from_url = U('Examine/indexs',array('type'=>$type));
                    $from_text = '审核不通过列表';
                    $to_form_url = '';
                    break;
                case '5':
                    $from_url = U('Padtrial/renew_padtrial',['id'=>$id]);
                    $from_text = '续借电审列表';
                    $to_form_url = U('Padtrial/padtrial',['id'=>$id]);
                    break;
                default:
                    $from_url = U('Examine/index',array('type'=>$type));
                    $from_text = '初次未审核列表';
                    $to_form_url = '';
            }
            $this->assign('from_url', $from_url);
            $this->assign('from_text', $from_text);
            $this->assign('to_form_url', $to_form_url);

            $this->assign( 'log', $log );
            $this->assign( 'logs', $logs );

            $this->assign( 'order', $result );
            $this->assign( 'type', $type );
            $this->display();
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function hinfo()
    {
        $this->info();
    }

    public function save()
    {
        $date = I( 'post.options' );
        //是否是续借
        $renew = I('get.renew');
        if(!empty( $date )) {
            $type = I( 'get.display', 0 );//0表示不通过
            if(!is_numeric( $date['amount'] )) {
                $this->error( '请选择正确的额度！' );
            }
            $amounts = get_amount_list( $date['amount'] );
            if(empty( $amounts )) {
                $this->error( '请选择正确的额度！' );
            }
            $noin_array=['0','6','7','9'];
            $sta = $this->model->where( [ 'id' => $date['id'] ] )->field( 'order_id,status,renew' )->find();
            if(!in_array($sta['status'],$noin_array)) {
                $this->error( '该借款已审核!' );
            }
            $amount = $amounts['amount'];
            $interest = $amounts['interest'];
            $examine = $amounts['examine'];
            $consulting = $amounts['consulting'];
            switch($date['loan_day']) {
                case '2':
                    $loan_day = 14;
                    break;
                case '3':
                    $loan_day = 21;
                    break;
                case '4':
                    $loan_day = 28;
                    break;
                default:
                    $loan_day = 7;
            }
            switch($date['stages']) {
                case '2':
                case '3':
                case '4':
                    $stages = $date['stages'];
                    break;
                default:
                    $stages = 1;
            }
            if(empty( $type )) {
                $dt = [
                    'status' => 6,
                    'lastuser_id' => get_current_admin_id(),
                    'lastuser_name' => cookie( "admin_username" ),
                    'modtime' => date( 'Y-m-d H:i:s' ),
                    'loan_day' => $loan_day,
                    'interest' => $interest,
                    'examine' => $examine,
                    'consulting' => $consulting,
                    'stages' => $stages,
                    'amount' => $amount,
                ];
                //审核不通过，那么用户就需要重新验证
                $this->user_model->where( [ 'id' => $date['user_id'],'type_borr'=>2 ] )->save( ['type_borr'=>1] );//从2变成1（如果不通过）
            } else {
                $dt = [
                    'status' => 10,
                    'lastuser_id' => get_current_admin_id(),
                    'lastuser_name' => cookie( "admin_username" ),
                    'modtime' => date( 'Y-m-d H:i:s' ),
                    'loan_day' => $loan_day,
                    'interest' => $interest,
                    'examine' => $examine,
                    'consulting' => $consulting,
                    'stages' => $stages,
                    'amount' => $amount,
                    'endtime' => date( 'Y-m-d', strtotime( '+' . $loan_day . ' days' ) ),
                ];
                $us = [ 'type_borr' => '2' ];
                $this->user_model->where( [ 'id' => $date['user_id'] ] )->save( $us );
            }
            //如果是从“审核不通过列表”过来
            $fromType = I('get.type',0);
            if($fromType=='6,9'){
                $sql = "UPDATE orders SET `overdue_m_status`=null WHERE id=".$date['id'];
                $this->model->execute($sql);
            }
            $dt['loan_amount'] = $dt['amount'];
            $this->model->where( [ 'id' => $date['id'] ] )->save( $dt );
            set_log( $date['id'], 6, $type ? '1' : '0', $date['messgae'] );
            $url = $this->jum_url . "?app_act=index/wechat_r_f";
            $post_data = [
                'id' => $date['user_id'],
                'amount' => $type ? 1 : 0,
                'type' => 1,
                'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $date['user_id'] ),
            ];
            A( 'indexlinks' )->http_post( $url, $post_data );
            if(empty($sta['renew']) && !empty($type) && !empty($date['messgae'])){//初次记录
                $d = [
                    'user_id' => $date['user_id'],
                    'examine_id' => get_current_admin_id(),
                    'message' => $date['messgae'],
                    'status' => 1,
                    'types' => 2,
                    'amount' => 0,
                    'deposit' => 0,
                ];
                M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $d );
            }
            $location_url = empty($date['from_url'])?U( "Examine/cntinued", [ 'type' => $type ] ):$date['from_url'];
            $this->success( "审核成功！",  htmlspecialchars_decode($location_url));
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 放款审核
     */
    public function fkinfo()
    {
        $id = I( 'get.id', 0 );
        if($id) {
            $type = I( 'get.type', 0 );
            $result = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( [ "a.id" => $id ] )
                ->field( 'b.bank,b.silver_card,b.silver_number,b.account_status,b.name,b.mobile,a.*' )->find();
            //log
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $result['id'] . ' and types<8 and types>0 and types!=2' )->order( 'crtime desc' )->select();
            $logs = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $result['user_id'] . ' and types=2' )->order( 'crtime desc' )->select();
            $ids = [];
            foreach($log as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            foreach($logs as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            if(!empty( $ids )) {
                $users = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                $user = [];
                foreach($users as $v) {
                    $user[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $user );
            }
            $this->system_amount = xu_amount([$result]);

            $this->assign( 'log', $log );
            $this->assign( 'logs', $logs );

            $this->assign( 'order', $result );
            $this->assign( 'type', $type );
            $this->display();
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function fksave()
    {
        $date = I( 'post.options' );
        $times = time();
        if(!empty( $date['id'] ) && !empty( $date['user_id'] )) {
            $type = I( 'get.display', 0 );
            $order = $this->model->where( [ 'id' => $date['id'], 'user_id' => $date['user_id'] ] )
                ->field( 'loan_day,order_id,amount,stages,id,user_id,interest,examine,consulting,status' )
                ->find();
            if($order['status'] != '10') {
                $this->error( '请选择正确的借款!' );
            }
            if(empty( $type )) {
                $dt = [ 'status' => 9 ];
                $status = 0;
                $msg = !empty( $date['message'] ) ? $date['message'] : '确认放款失败';
            } else {
                $dt = [ 'status' => 8 ];
                $status = 1;
                $msg = '确认放款成功';
                $order['loan_day']-=1;
                $dt['endtime'] = date( 'Y-m-d', strtotime( '+' . $order['loan_day'] . ' days', $times ) );
                $dt['loan_time'] = date( 'Y-m-d' );
                $us = M( 'users' )->where( [ 'id' => get_current_admin_id() ] )->field( 'user_login' )->find();
                $dt['loan_user'] = $us['user_login'];
                //加插一个日均逾期费
                //用$order找一下额度配置（费用详情）
                $config = xu_amount([$order]);
                $dt['overdue_due_per'] = $config['overdue_fee'];//更新一下最新的逾期费
                //插入订单保证金表记录
                $system_amount = xu_amount([$order]);
                if(intval($system_amount['bond_amount'])>0){
                    $bond_amount = $system_amount['bond_amount'];
                    $bond_data['user_id'] = $date['user_id'];
                    $bond_data['order_id'] = $date['id'];
                    $bond_data['bond_amount'] = $bond_amount;
                    $bond_data['is_back'] = 0;
                    $bond_data['is_deal'] = 0;
                    M('order_bond','system_',C('DB_CONFIG2'))->add($bond_data);
                }
            }
            set_log( $date['id'], 1, $status, $msg, '', '', $order['amount'] - $order['interest'] - $order['examine'] - $order['consulting'] - 10 );
            if(!empty( $type )) {//成功时才有资金变化
                $msg2 = $order['order_id'] . '借款成功';
                set_log( $date['user_id'], 0, $status, $msg2, 'jie', $date['id'] );

                set_log( $date['user_id'], 0, $status, $order['order_id'] . '咨询费', 'free_other', $date['id'], 1 );
                set_log( $date['user_id'], 0, $status, $order['order_id'] . '审核费', 'free_other', $date['id'], 2 );
                set_log( $date['user_id'], 0, $status, $order['order_id'] . '顾问费', 'free_other', $date['id'], 3 );
                set_log( $date['user_id'], 0, $status, $order['order_id'] . '提现手续费', 'free_other', $date['id'], 4 );

                $msg2 = '申请提现';
                set_log( $date['user_id'], 0, $status, $msg2, 'kou', $date['id'] );

                //分期 子订单
                $day = floor($order['loan_day'] / $order['stages']);
                $amount = ceil( $order['amount'] / $order['stages'] );
                $times = date( 'Y-m-d', $times );
                $dts=[];
                for($i = 1; $i <= $order['stages']; $i++) {
                    $times = date( 'Y-m-d', strtotime( '+' . $day . ' days', strtotime( $times ) ) );
                    $dts[] = [
                        'pid' => $order['id'],
                        'user_id' => $order['user_id'],
                        'stages' => $i,
                        'endtime' => $times,
                        'amount' => $amount,
                        'loan_day' => $day,
                    ];
                }
                $this->sub_model->addAll( $dts );
                $dt['endtime'] =$times;
//                $url = $this->jum_url . "?app_act=index/wechat_r_f";
//                $post_data = [
//                    'id' => $date['user_id'],
//                    'amount' => $order['amount'],
//                    'type' => 2,
//                    'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $date['user_id'] ),
//                ];
//                A( 'indexlinks' )->http_post( $url, $post_data );
                $this->user_model->where( [ 'id' => $date['user_id'] ] )->save( [ 'is_renew' => 1 ] );
                //解套
                if(!empty($date['principal'])){
                    $add=[
                        'oid'=>$date['id'],
                        'user_id'=>$date['user_id'],
                        'amount'=>$order['amount'],
                        'principal'=>$order['amount'] - $order['interest'] - $order['examine'] - $order['consulting'] - 10,
                    ];
                    M( "unlock", 'orders_', C( 'DB_CONFIG2' ) )->add($add);
                }
                //分销 获取金额
                $user = $this->user_model->where( [ 'id' => $date['user_id'] ] )->field( 'code,is_adult' )->find();
                if(!empty( $user['code'] )){//推荐人不为空
                    $this->commission(1,$user['code'],$date['user_id'],$user['is_adult'],$order['id']);
                }
            }
            $this->model->where( [ 'id' => $date['id'] ] )->save( $dt );
            //推送用户通知 ---- start
            if(empty( $type )) {//放款失败
                $getui_config['title'] = '您的借款申请放款失败';
                $getui_config['content'] = '您的借款申请放款失败';
            }else{//放款成功
                $getui_config['title'] = '恭喜,您的借款申请已放款成功';
                $getui_config['content'] = '恭喜,您的借款申请已放款成功';
            }
            $user_id = $date['user_id'];
            $user = $this->user_model->where(['id'=>$user_id])->field('gt_client_id')->find();
            if(!empty($user['gt_client_id'])){
                $gt_client_id = $user['gt_client_id'];
                //获取推送结果 - errorCode 0成功 1失败  这里不做处理
                $query = $this->getui_by_clientid($gt_client_id,1,$getui_config);
                //推送用户通知 ---- end
            }
            $this->success( "审核成功！", U( "Examine/loan_last" ) );
        } else {
            $this->error( '数据传入失败！' );
        }
    }
    /*
     * 分销提成
     */
    public function commission($level=1,$code='',$user_id='',$is_adult=0,$oid=''){
        if($level>3){
            return false;
        }
        if(empty($code) || empty($user_id) || empty($oid)){
            return false;
        }
        if(empty($is_adult)){
            $is_adult=1;
        }
        $fen = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'code' => $code, 'is_dis' => 1 ] )->field( 'pid,user_id,agent_id,is_level' )->find();
        if(empty($fen)){//没找到代理则返回
            return;
        }
        if(empty($fen['agent_id']) || empty($fen['pid'])){
            if($level==1){
                $level=0;
            }
        }
        $time=date('Y-m-d H:i:s');
        $agent=M( "distribution_amount", 'system_', C( 'DB_CONFIG2' ) )->field('amount_first,amount_first_stu,num,is_start')
            ->where(['level'=>$level])->where('(is_start=0 or is_start>="'.$time.'")')
            ->order('crtime desc')->find();
        if(empty($agent) || empty($agent['num'])){
            return;
        }
        $num = M( "distribution_log", 'system_', C( 'DB_CONFIG2' ) )->where( ['user_id' => $user_id,'fuser_id'=>$fen['user_id'], 'type' => 1 ] )->field( 'user_id' )->count();
        $num=empty($num)?0:$num;
        if($agent['num']<=$num){//超过次数 则拿不到提成
            return;
        }
        if($is_adult == 2) {
            $amounts = $agent['amount_first_stu'];
        } else {
            $amounts = $agent['amount_first'];
        }
        $insert = [
            'user_id' => $user_id,
            'fuser_id' => $fen['user_id'],
            'amount' => $amounts,
            'status' => 0,
            'type' => 1,
        ];
        M( "distribution_log", 'system_', C( 'DB_CONFIG2' ) )->add( $insert );
        if(!empty($fen['agent_id'])){
            $insert = [
                'oid'=>$oid,
                'user_id'=>$user_id,
                'agent_id'=>$fen['agent_id'],
                'a_pid'=>$fen['pid'],
                'amount'=>$amounts,
                'level'=>$fen['is_level'],
                'segments'=>$level,
            ];
            M( "distr_amount_log", 'system_', C( 'DB_CONFIG2' ) )->add( $insert );
        }
        $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $fen['user_id'] ] )->field( 'deposit' )->find();
        $d = [
            'user_id' => $fen['user_id'],
            'examine_id' => 0,
            'message' => '钱友奖励',
            'status' => 1,
            'types' => 9,
            'amount' => $amounts,
            'deposit' => $amounts + $yue['deposit'],
        ];
        M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $d );
        M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $fen['user_id'] ] )->setInc( 'deposit', $amounts );
        if(!empty($fen['pid']) && !empty($fen['agent_id'])){
            $pid=M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $fen['pid'], 'is_dis' => 1 ] )->field( 'code' )->find();
            if(!empty($pid['code'])){
                $level=$level+1;
                $this->commission($level,$pid['code'],$user_id,$is_adult,$oid);
            }
        }
        return true;
    }
    /*
     * 贷后未到期
     * 借款中
     * ① 不催缴列表
     */
    function loan_no_due($type = '1,8', $desc = 'DESC', $byuser = false, $chui = 0)
    {
        //判断是否是未到期列表
        $isWeiDaoList = false;
        '1,8' === $type && 'DESC' === $desc && false === $byuser && 0 === $chui && ($isWeiDaoList = true);
        //判断是否已是已到期列表
        $isDaoList = false;
        $type === 4 && 'ASC' === $desc && true === $byuser && 0 === $chui && ($isDaoList = true);
        //判断是否是已还款列表
        $isYiHuanList = false;
        $type === 2 && 'DESC' === $desc && ($isYiHuanList = true);
        //判断是否是不催缴列表
        $isBuCuiList = false;
        3 === $type && 'desc' === $desc && false === $byuser && 1 === $chui && ($isBuCuiList = true);

        //判断是否要合计
        $isNeedTotal = false;
        if($isWeiDaoList || $isDaoList || $isYiHuanList || $isBuCuiList){
            $isNeedTotal = true;
        }


        $type = I( 'get.type', 0 ) ? I( 'get.type', 0 ) : $type;
        $where = [];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts', 0 )) {
            $where[] = 'a.endtime >= "' . $name . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] = 'a.endtime <= "' . $name . '"';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = 'a.loan_time >= "' . $name . '"';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = 'a.loan_time <= "' . $name . '"';
        }
        if($loan_user = I('request.loan_user')){
            $where[] = 'a.loan_user like "%'.$loan_user.'%"';
        }
        if($loan_user = I('request.shenhe')){
            $where[] = 'a.lastuser_name like "%'.$loan_user.'%"';
        }
        if($name = I( 'request.fengkong', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers in (0)';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.caiwu', 0 )) {
            //$ur=M('users')->field('id')->where('user_login like "%'.$name.'%"')->select();
//            if(empty($ur)){
//                $where[]='a.loan_user in (0)';
//            }else{
//                $i=array();
//                foreach($ur as $v){
//                    $i[]=$v['id'];
//                }
//                $where[]='a.loan_user in ('.implode(',',$i).')';
//            }
            $where[] = 'a.loan_user like "%' . $name . '%"';
        }
        if($name = I('request.daihou',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan in (' . implode( ',', $i ) . ')';
            }
        }
        if($type == 2) {
            $type = I( 'request.status' );
            if($type == '0') {
                $type = '1,2,3,4,8';
            }
            if($type == '') {
                $type = 2;
            }
            //查找贷后专员
            $daihou_list = M( 'users' )->where( 'user_status=1')->getField('id,user_login');
            $this->assign('daihou_list',$daihou_list);
        } else if($type == 3) {
            $where[] = 'a.is_ban = "' . $chui . '"';
        }
        if($byuser) {
            $byuser = I( 'request.byusers', 0 );
            if($byuser == 0) {
                $byuser = 3;
            }
            $group = get_groups_admin_user();
            switch($byuser) {
                case '1':
                    $where[] = 'b.byusers_loan=0';
                    break;
                case '3':
                    if($group == 5) {
                        $where[] = 'b.byusers_loan in (0,' . get_current_admin_id() . ')';
                    }
                    break;
                default:
                    $where[] = 'b.byusers_loan =' . get_current_admin_id();
            }
        } else {
            $group = get_groups_admin_user();
            if($group == 5) {
                $where[] = 'b.byusers_loan in (0,' . get_current_admin_id() . ')';
            }
        }
        switch (I( 'request.ordnum',0)){
            case '1':
                $where[] = 'a.renew =0';
                break;
            case '2':
                $where[] = 'a.renew =1';
                break;
        }
        $is_adult = I( 'request.is_adult', -1 );
        if(-1!=$is_adult) {
            $where[] = 'b.is_adult = '.$is_adult;
        }
        $where[] = 'a.status in (' . $type . ')';
        $count = $this->model->join( "LEFT JOIN system_user b on a.user_id=b.id" )->where( implode( ' and ', $where ) )->count();
        $page = $this->page( $count, 20 );
        $list = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            //->join( "LEFT JOIN system_distribution c on c.code=b.code" )
            ->where( implode( ' and ', $where ) )
            ->order( "a.loan_time " . $desc . ",a.id desc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
           // ->field( 'b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,a.*,c.name as dis_name' )
            ->field( 'b.is_adult,b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,a.*,b.code' )
            ->select();
        //是否需要合计
        if($isNeedTotal){
            $for_total = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( implode( ' and ', $where ) )
                ->field( 'sum(a.amount) as total_amount')
                ->find();
            $this->assign($for_total);
        }

        //如果是已到期列表，查到已经申请续期的记录，不能再次显示续期按钮
        if($isDaoList && !empty($list)){
            //拿到订单ID列表
            $oids = array_column($list,'id');
            //查询续期列表
            if(!empty($oids)){
                $rids = M('renewal','orders_',C('DB_CONFIG2'))->where(['status'=>0,'pid'=>['in',$oids]])->getField('id',true);
                $this->assign('rids',$rids);
            }
        }
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan'] )) {
                $ids[$v['byusers_loan']] = $v['byusers_loan'];
            }
            if(!empty( $v['byusers'] )) {
                $ids[$v['byusers']] = $v['byusers'];
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $codes = [];
        foreach($list as $v) {
        	if(!empty( $v['code'] )) {
        		$codes[$v['code']] = '"'.$v['code'].'"';
        	}
        }

        if(!empty( $codes )) {
        	$c = [];
        	$co = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->field( 'code,name' )->select();
        	foreach($co as $v) {
        		$c[$v['code']] = $v['name'];
        	}
        	$this->assign( 'codes', $c );
        }
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 到期
     */
    function loan_expire()
    {
        //已加入黑名单的用户Id
        $b_where = 'user_type = 0 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>'.time().'))';
        $this->b_id_list = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->getField('user_id',true);
        //已加入白名单的用户Id
        $w_where = 'user_type = 1 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>'.time().'))';
        $this->w_id_list = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($w_where)->getField('user_id',true);

        $this->loan_no_due( 4, 'ASC', true );
    }

    function loan_expire_buyer($type = '4', $desc = 'DESC')
    {
        $type = I( 'get.type', 0 ) ? I( 'get.type', 0 ) : $type;
        $where = [];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts', 0 )) {
            $where[] = 'a.endtime >= "' . $name . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] = 'a.endtime <= "' . $name . '"';
        }
        if($type == 3) {
            $type = I( 'request.status' );
            if($type == '0') {
                $type = '1,2,3,4,8';
            }
            if($type == '') {
                $type = 2;
            }
        }
        //当订单为逾期订单的时候
//        if($type == 3) {
//            $status = I('request.status',0);
//            if($status!=0){//0为全部
//                $where[] = 'a.status = '.$status;
//            }
//        }
        $where[] = 'b.byusers_loan =' . get_current_admin_id();
        $where[] = 'a.status in (' . $type . ')';
        $count = $this->model->join( "LEFT JOIN system_user b on a.user_id=b.id" )->where( implode( ' and ', $where ) )->count();
        $page = $this->page( $count, 20 );
        $list = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=3" )
            ->where( implode( ' and ', $where ) )
            ->order( "d.endtime desc,a.loan_time " . $desc . ",a.id desc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->field( 'b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,
             a.id,a.order_id,a.user_id,a.status,a.amount,a.crtime,a.endtime,a.loan_day,a.loan_time,a.loan_amount,a.stages,a.lastuser_id,a.lastuser_name,a.loan_user' )
            ->select();
        //判断是否需要合计
        if(!empty($list)){
            $for_total = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=3" )
                ->where( implode( ' and ', $where ) )
                ->field( 'sum(a.amount) as total_amount' )
                ->find();
            $this->assign($for_total);
        }
        $ids = [];
        foreach($list as $v) {
            if(empty( $v['byusers_loan'] )) {
                continue;
            }
            $ids[$v['byusers_loan']] = $v['byusers_loan'];
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 已还款
     */
    function loan_repaid()
    {
        $this->loan_no_due( 2, 'DESC' );
    }

    /**
     * @use          [得到已还款未续借列表的查询条件]
     * @author       chenxiaogang
     * @return string
     */
    private function get_has_not_renew_repayment_list_condition(){
        $where = [];
        if($name = I( 'request.name', 0 )) {
            $where[] = ' b.name like "%' . $name . '%" ';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = ' b.mobile like "%' . $name . '%" ';
        }
        if($name = I( 'request.starts', 0 )) {
            $where[] = ' a.endtime >= "' . $name . '" ';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] = ' a.endtime <= "' . $name . '" ';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = ' a.loan_time >= "' . $name . '" ';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = ' a.loan_time <= "' . $name . '" ';
        }
        if($name = I( 'request.caiwu', 0 )) {
            $where[] = ' a.loan_user like "%' . $name . '%" ';
        }
        //客户类型 -1全部 0未知 1成人 2学生
        $is_adult = I( 'request.is_adult', -1 );
        if(-1!=$is_adult) {
            $where[] = ' b.is_adult = "'.$is_adult. '" ';
        }
        //$must = 'and a.renew=0 and a.status=2 and a.user_id not in(select user_id from orders where renew=1 group by user_id)';
        $must = 'and a.id in(SELECT max(id) FROM orders where `status`=2 group by user_id) and b.type=5 and b.type_borr=1';
        ///$must = 'and a.id in(SELECT max(id) FROM orders where `status`=2 group by user_id) and b.is_renew=1 and b.renew=0';
        $whereStr = ltrim(implode( ' and ', $where ).$must,'and');//排除后期含有续期订单的用户订单
        return $whereStr;
    }

    /**
     * @use          [已还款未续借列表]
     * @author       chenxiaogang
     */
    public function has_not_renew_repayment_list()
    {
        $loan_count_order = I('request.loan_count_order', 0);
        if('0'==$loan_count_order){
            $loan_order_str = 'ru.all_loan_count DESC,';
        }else{
            $loan_order_str = 'ru.all_loan_count,';
        }
        $whereStr = $this->get_has_not_renew_repayment_list_condition();//得到查询条件
        $count = $this->model->join( "LEFT JOIN system_user b on a.user_id=b.id" )->where( $whereStr )->count();
        $page = $this->page( $count, 20 );
        $list = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->join( "LEFT JOIN report_current_users ru on ru.user_id=a.id" )
            ->where( $whereStr  )
            ->order( $loan_order_str."a.loan_time DESC,a.id desc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->field( 'b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,a.*,
            b.code,b.is_adult,IFNULL(ru.all_loan_count,0) AS all_loan_count' )
            ->select();
        //判断是否需要合计
        if($count>0){
            $for_total = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( $whereStr  )
                ->field( 'sum(a.amount) as total_amount' )
                ->find();
            $this->assign($for_total);
        }
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan'] )) {
                $ids[$v['byusers_loan']] = $v['byusers_loan'];
            }
            if(!empty( $v['byusers'] )) {
                $ids[$v['byusers']] = $v['byusers'];
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['code'] )) {
                $codes[$v['code']] = '"'.$v['code'].'"';
            }
        }
        if(!empty( $codes )) {
            $c = [];
            $co = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->field( 'code,name' )->select();
            foreach($co as $v) {
                $c[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $c );
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 还款详情
     */
    function due_info()
    {
        $this->repayment();
    }

    /*
     * 逾期
     */
    function loan_overdue($type = '3', $desc = 'DESC', $byuser = true, $chui = 0)
    {
        //$type=I('get.type',0)?I('get.type',0):$type;
        $where = [
           // 'a.is_third=0',
        ];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = 'a.loan_time >= "' . $name . '"';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = 'a.loan_time <= "' . $name . '"';
        }
        if($name = I( 'request.fengkong', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers in (0)';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.caiwu', 0 )) {
            $where[] = 'a.loan_user like "%' . $name . '%"';
        }
        if($name = I('request.daihou',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan in (' . implode( ',', $i ) . ')';
            }
        }
        //客户类型 -1全部 0未知 1成人 2学生
        $is_adult = I( 'request.is_adult', -1 );
        if(-1!=$is_adult) {
            $where[] = 'b.is_adult = '.$is_adult;
        }
        if($type == 2) {
            $type = I( 'request.status' );
            if($type == '0') {
                $type = '1,2,3,4,8';
            }
            if($type == '') {
                $type = 2;
            }
        } else if($type == 3) {
            $where[] = 'a.is_ban = "' . $chui . '"';
        }
        if($byuser) {
            $byuser = I( 'request.byusers', 0 );
            if($byuser == 0) {
                $byuser = 3;
            }
            $group = get_groups_admin_user();
            switch($byuser) {
                case '1':
                    $where[] = 'b.byusers_loan=0';
                    break;
                case '3':
                    if($group == 5) {
                        $where[] = 'b.byusers_loan in (0,' . get_current_admin_id() . ')';
                    }
                    break;
                default:
                    $where[] = 'b.byusers_loan =' . get_current_admin_id();
            }
        } else {
            $group = get_groups_admin_user();
            if($group == 5) {
                $where[] = 'b.byusers_loan in (0,' . get_current_admin_id() . ')';
            }
        }
        if($name = I( 'request.mone', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m1=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m1 in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mtwo', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m2=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m2 in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mthree', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m3=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m3 in (' . implode( ',', $i ) . ')';
            }
        }
        $where[] = 'a.status in (' . $type . ')';
        $where[]='d.status=3';
        $other_where=['d.id in (e.id)'];
        if($name = I( 'request.starts', 0 )) {//区分时间
            $other_where[] = 'd.endtime >= "' . date('Y-m-d',strtotime('-1days',strtotime($name))) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $other_where[] = 'd.endtime <"' . $name . '"';
        }
        if($overdue_m_status = I( 'request.overdue_m_status', -1 )) {
            if($overdue_m_status!=-1){
                $other_where[] = 'a.overdue_m_status ='.$overdue_m_status;
            }
        }
        if($collection_type = I( 'request.collection_type', -1 )) {
            if($collection_type!=-1){
                $where[] = 'b.collection_type like "%'.$collection_type.'%"';
            }
        }
        if($name = I('request.qudao',0)){
            $ur = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->field( 'code' )->where( 'name like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = "'".$v['code']."'";
                }
                $where[] = 'b.code in (' . implode( ',', $i ) . ')';
            }
        }
        //$sql='select count(a.id) as counts from (SELECT a.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id ORDER BY d.endtime) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ) a  ';
        $sql='SELECT count(a.id) as counts FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC ';
        $count=$this->model->query($sql);
        $page = $this->page( count($count), 20 );

//        $list = $this->model
//            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
//           // ->join( "LEFT JOIN system_distribution c on c.code=b.code" )
//            ->join( "LEFT JOIN orders_sub d on d.pid=a.id" )
//            ->where( implode( ' and ', $where ) )
//            ->order( "d.endtime asc,a.loan_time " . $desc . ",a.id desc" )
//            ->limit( $page->firstRow . ',' . $page->listRows )
//            //->field( 'b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,a.*,c.name as dis_name,d.endtime as sub_endtime' )
//            ->field('b.name,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,b.code,d.endtime as sub_endtime,a.overdue_m_status,
//            a.id,a.order_id,a.user_id,a.status,a.amount,a.crtime,a.endtime,a.loan_day,a.loan_time,a.loan_amount,a.stages,a.lastuser_id,a.lastuser_name,a.loan_user' )
//            ->group( 'a.order_id' )
//            ->select();
        $sql='SELECT b.collection_type,b. NAME,b.mobile,b.code,b.is_adult,b.account_status,b.identity,b.byusers_loan,b.byusers_loan_m1,b.byusers_loan_m2,b.byusers_loan_m3,b.byusers,b. CODE,d.endtime AS sub_endtime,a.overdue_m_status,a.id,a.order_id,a.user_id,a. STATUS, a.amount, a.crtime, a.endtime,a.loan_day,a.loan_time, a.loan_amount, a.stages, a.lastuser_id,a.lastuser_name,a.loan_user FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d  GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC limit '.$page->firstRow . ',' . $page->listRows;
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $list=$this->model->query($sql);
        //print_r($sql);exit;
        //查到已经申请续期的记录，不能再次显示续期按钮
        if(!empty($list)){
            //拿到订单ID列表
            $oids = array_column($list,'id');
            //查询续期列表
            if(!empty($oids)){
                $rids = M('renewal','orders_',C('DB_CONFIG2'))->where(['status'=>0,'pid'=>['in',$oids]])->getField('id',true);
                $this->assign('rids',$rids);
            }
            //统计合计
            $sql='SELECT a.amount FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d  GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ';
            $for_total = $this->model->query($sql);
            $for_total = [
                'total_amount'=>array_sum(array_column($for_total,'amount')),
            ];
            $this->assign($for_total);
        }
        $ids = [];
        $codes=[];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan_m1'] )) {
                $ids[$v['byusers_loan_m1']] = $v['byusers_loan_m1'];
            }
            if(!empty( $v['byusers_loan_m2'] )) {
                $ids[$v['byusers_loan_m2']] = $v['byusers_loan_m2'];
            }
            if(!empty( $v['byusers_loan_m3'] )) {
                $ids[$v['byusers_loan_m3']] = $v['byusers_loan_m3'];
            }
            if(!empty( $v['byusers_loan'] )) {
                $ids[$v['byusers_loan']] = $v['byusers_loan'];
            }
            if(!empty( $v['byusers'] )) {
                $ids[$v['byusers']] = $v['byusers'];
            }
            if(!empty( $v['code'] )) {
                $codes[] = "'" . $v['code'] . "'";
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        //已加入黑名单的用户Id
        $b_where = 'user_type = 0 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>'.time().'))';
        $this->b_id_list = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->getField('user_id',true);
        if($type==3){
            $shen_user = M( "users a" )->field('a.id,a.user_login')
                ->join('left join cmf_role_user b on b.user_id=a.id')
                ->where( "role_id=5 and a.user_status=1" )
                ->order( 'a.id DESC' )->select();
            $this->assign( 'shen_user', $shen_user );
            if(!empty( $codes )) {
                $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
                $is_ids = [];
                foreach($is_id as $v) {
                    $is_ids[$v['code']] = $v['name'];
                }
                $this->assign( 'codes', $is_ids );
            }
        }
        $collection_types=M( "collection_type", 'system_', C( 'DB_CONFIG2' ) )->field('id,name')->where(['is_true'=>1])->select();
        $collection_type=[];
        foreach($collection_types as $v){
            $collection_type[$v['id']]=$v['name'];
        }
        $this->assign( 'collection_type', $collection_type );
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 转让贷后
     */
    function transferDaihou()
    {
        $data = I( 'request.' );
        if(empty( $data['us_id'] ) || empty( $data['users'] )) {
            $this->error( '数据传入失败！' );
        }
        switch ($data['display']){
            case 'M1':
                $str='byusers_loan_m1';
                break;
            case 'M2':
                $str='byusers_loan_m2';
                break;
            case 'M3':
                $str='byusers_loan_m3';
                break;
            default:
                $str='byusers_loan';
        }
        $user = explode( ',', $data['users'] );
        foreach($user as $k => $v) {
            if(!is_numeric( $v ) || empty( $v )) {
                unset( $user[$k] );
            }
        }
        if(empty( $user )) {
            $this->error( '数据传入失败！' );
        }
        $lastuser = get_current_admin_id();
        $user_list = M( "user", 'system_', C( 'DB_CONFIG2' ) )->field( 'id,'.$str )->where( 'id in (' . implode( ',', $user ) . ')' )->select();
        $ins = [];
        foreach($user_list as $v) {
            $ins[] = [
                'user_id' => $v['id'],
                'bfuser_id' => empty( $v[$str] ) ? 0 : $v[$str],
                'auser_id' => $data['us_id'],
                'lastuser_id' => $lastuser,
            ];
            $up = [
                $str => $data['us_id'],
            ];
            M( "user", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $v['id'] ] )->save( $up );
        }
        M( "trf_log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $ins );
        $this->success( "转让成功！", U( "indexadmin/index" ) );
    }

    /**
     * 逾期M1列表
     */
    function loan_overdue_m1()
    {
        $this->loan_overdue_mnum(1);
        $this->display();
    }

    /**
     * 逾期M2列表
     */
    function loan_overdue_m2()
    {
        $this->loan_overdue_mnum(2);
        $this->display();
    }

    /**
     * 逾期期数
     * @param $m_status M状态 例如:M1 1即为状态
     */
    public function loan_overdue_mnum($m_status=1){
        $where = [];
        $where[] = 'a.overdue_m_status = '.$m_status;
        $where= $this->m_overdue_common_where($where);
        $other_where=[];
        if($name = I( 'request.starts', 0 )) {//区分时间
            $other_where[] = 'd.endtime >= "' . date('Y-m-d',strtotime('-1days',strtotime($name))) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $other_where[] = 'd.endtime <"' . $name . '"';
        }
        //合计
        $for_total = $this->model
            ->field( 'a.amount' )
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=3" )
            ->where( implode(' and ',array_merge_recursive($where,$other_where)) )
            ->group( 'a.order_id' )
            ->select();
        $other_where[]='d.id in (e.id)';
        //$sql='SELECT a.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id ) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ';
        $sql='select count(a.id) as counts from (SELECT a.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id  ) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ) a  ';
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $count=$this->model->query($sql);
        $page = $this->page( $count[0]['counts'], 20 );
        $sql='SELECT b. NAME,b.mobile,b.account_status,b.identity,b.byusers_loan,b.byusers,b.CODE,d.endtime AS sub_endtime,a.overdue_m_status,a.id,a.order_id,a.user_id,a. STATUS, a.amount, a.crtime, a.endtime,a.loan_day,a.loan_time, a.loan_amount, a.stages, a.lastuser_id,a.lastuser_name,a.loan_user FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d  GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC limit '.$page->firstRow . ',' . $page->listRows;
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $list=$this->model->query($sql);
        $for_total = array(
            'total_amount'=>array_sum(array_column($for_total,'amount'))
        );
        $this->assign($for_total);
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan'] ))
                $ids[$v['byusers_loan']] = $v['byusers_loan'];
            if(!empty( $v['byusers'] ))
                $ids[$v['byusers']] = $v['byusers'];
            if(!empty( $v['daihou_id'] ))
                $ids[$v['daihou_id']] = $v['daihou_id'];
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v)
                $u[$v['id']] = $v['user_login'];
            $this->assign( 'users', $u );
        }
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['code'] ))
                $codes[$v['code']] = '"'.$v['code'].'"';
        }
        if(!empty( $codes )) {
            $c = [];
            $co = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->field( 'code,name' )->select();
            foreach($co as $v)
                $c[$v['code']] = $v['name'];
            $this->assign( 'codes', $c );
        }
        //已加入黑名单的用户Id
        $b_where = 'user_type = 0 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>'.time().'))';
        $this->b_id_list = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->getField('user_id',true);

        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
    }

    /**
     * 逾期M期数Where组合方法
     * @param array $where
     */
    function m_overdue_common_where($where=[]){
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = 'a.loan_time >= "' . $name . '"';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = 'a.loan_time <= "' . $name . '"';
        }
        if($name = I( 'request.fengkong', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers in (0)';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.caiwu', 0 )) {
            $where[] = 'a.loan_user like "%' . $name . '%"';
        }
        if($name = I('request.daihou',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mtwo', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan in (0)';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan in (' . implode( ',', $i ) . ')';
            }
        }
        $byuser = I( 'request.byusers', 0 );
        if($byuser == 0) {
            $byuser = 3;
        }
        $group = get_groups_admin_user();
        switch($byuser) {
            case '1':
                $where[] = 'b.byusers_loan=0';
                break;
            case '3':
                if($group == 5) {
                    $where[] = 'b.byusers_loan in (0,' . get_current_admin_id() . ')';
                }
                break;
            default:
                $where[] = 'b.byusers_loan =' . get_current_admin_id();
        }
        $where[] = 'a.is_third = 0';
        $where[] = 'a.status = 3';
        $where[] = 'a.is_ban = 0';
        return $where;
    }

    /**
     * 修改订单逾期M状态
     * @param $id 订单Id
     * @param $to_m_status 修改的状态
     */
    public function edit_m_status($id,$to_m_status){
        if(!in_array($to_m_status,['1','2','3'])){
            $this->error('错误的逾期修改状态!');
        }
        $order_where['id'] = $id;
        $order_where['status'] = 3;
        $model = new Model();
        $mdb = $model->db(2,"DB_CONFIG2");
        $mdb->startTrans();
        $order = $mdb->table('orders')->where($order_where)->find();
        if(empty($order)){//查询不到该订单
            $this->error('错误的订单信息');
        }else{
            //判断订单状态只允许由M1=>M2=>M3
            $order_m_status = intval($order['overdue_m_status']);
            $to_m_status = intval($to_m_status);
            if($to_m_status<=$order_m_status){
                $this->error('无法修改订单逾期状态');
            }
            $sub_where['pid'] = $order['id'];
            $sub_where['status'] = 3;
            $sub_total = M('sub','orders_',C('DB_CONFIG2'))->where($sub_where)->SUM('amount');
            //添加订单逾期修改记录
            $r_data1['user_id'] = $order['user_id'];
            $r_data1['order_id'] = $id;
            $r_data1['record_note'] = '修改逾期状态M'.$order['overdue_m_status'].'到M'.$to_m_status.',剩余还款金额';
            $r_data1['record_note_value'] = empty($sub_total)?0:$sub_total;
            $r_data1['overdue_m_status'] = $to_m_status;
            $r_data1['record_type'] = 0;
            $r_data1['create_time'] = date('Y-m-d H:i:s',time());
            $r_data1['createby'] = get_current_admin_id();//登录管理员ID
            //添加订单指派专员记录
            $role = M( 'role' )->field( 'id' )->where("name ='M2'")->find();
            $users= M( 'users a' )->field( 'a.id,a.user_login' )
                ->join('left join cmf_role_user b on b.user_id=a.id')
                ->where("role_id=".$role['id'])->select();
            $user_buy=M( "user", 'system_', C( 'DB_CONFIG2' ) )->field('byusers_loan_m1')->where(['id'=>$order['user_id']])->find();
            $dh_user=$users[array_rand($users,1)];
            $r_data2['user_id'] = $user_buy['byusers_loan_m1'];
            $r_data2['order_id'] = $id;
            $r_data2['record_note'] = '为订单指派贷后专员:'.$dh_user['user_login'];
            $r_data2['record_note_value'] = $dh_user['id'];
            $r_data2['overdue_m_status'] = $to_m_status;
            $r_data2['record_type'] = 1;
            $r_data2['create_time'] = date('Y-m-d H:i:s',time());
            $r_data2['createby'] = get_current_admin_id();//登录管理员ID

            $all_data = [];
            array_push($all_data,$r_data1);
            array_push($all_data,$r_data2);

            $res1 = $mdb->table('system_overdue_record')->addAll( $all_data );
            if(false==$res1){
                $mdb->rollback();
                $this->error('状态修改失败');
            }

            //修改订单逾期状态
            $save_data['overdue_m_status'] = $to_m_status;
            //$save_data['daihou_id'] = $dh_user['id'];
            $res2 = $mdb->table('orders')->where($order_where)->save($save_data);
            M( "user", 'system_', C( 'DB_CONFIG2' ) )->where(array('id'=>$order['user_id']))->save(array('byusers_loan_m2'=>$dh_user['id']));
            if(false===$res2){
                $mdb->rollback();
                $this->error('状态修改失败');
            }

            $mdb->commit();
            $this->success('状态修改成功');
        }
    }

    /*
     * 逾期 - 我的客户
     */
    function loan_overdue_buyer()
    {
        //读取等级关系
        $levelModel = new \User\Model\AdminLevel();
        //查找自己以及自己的子级
        $adminId = get_current_admin_id();
        $sonIds = $levelModel->getSonIds($adminId);
        $selectIds = array_merge($sonIds,[$adminId]);
        $tree = [];
        if(!empty($sonIds)){
            $tree = $levelModel->buildOptionTreeByIds($sonIds);
        }
        $this->assign('is_has_tree',empty($tree)?0:1); //判断是否有子级
        $this->assign('tree',$tree);
        //3逾期+我的客户
        //$this->loan_expire_buyer( 3 );
        $type = 3;
        $type = I( 'get.type', 0 ) ? I( 'get.type', 0 ) : $type;
        $where = [];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($type == 3) {
            $type = I( 'request.status' );
            if($type == '0') {
                $type = '1,2,3,4,8';
            }
            if($type == '') {
                $type = 3;
            }
        }
        switch (I('request.disp')){
            case 'M1':
                $str='byusers_loan_m1';
                break;
            case 'M2':
                $str='byusers_loan_m2';
                break;
            case 'M3':
                $str='byusers_loan_m3';
                break;
            default:
                $str='byusers_loan';
        }
        //确定等级where
        if(I('request.dh_level')!=''){
            $dh_level = I('request.dh_level');
            if($dh_level === 'a'){//全部包括自己
                $where[] = 'b.'.$str.' in('.implode(',',$selectIds).')';
            }elseif($dh_level === 'b'){//全部不包括自己
                $where[] = 'b.'.$str.' in('.implode(',',$sonIds).')';
            }else{
                $where[] = 'b.'.$str.' =' . intval($dh_level);//指定某个下级
            }
        }else{
            $where[] = 'b.'.$str.' =' . get_current_admin_id();//默认只展示自己的
        }
        $where[] = 'a.status in (' . $type . ')';
        $other_where=[];
        if($name = I( 'request.starts', 0 )) {//区分时间
            $other_where[] = 'd.endtime >= "' . date('Y-m-d',strtotime('-1days',strtotime($name))) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $other_where[] = 'd.endtime <"' . $name . '"';
        }
        //合计
        $for_total = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=3" )
            ->where( implode(' and ',array_merge_recursive($where,$other_where)) )
            ->field( 'sum(a.amount) as total_amount' )
            ->find();
        $other_where[]='d.id in (e.id)';
        $sql='select count(a.id) as counts from (SELECT a.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id ORDER BY d.endtime ASC,a.loan_time DESC,a.id DESC ) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC) a  ';
        $count=$this->model->query($sql);
        $page = $this->page( $count['0']['counts'], 20 );
        $sql='SELECT b. NAME,b.mobile,b.account_status,b.identity,b.'.$str.',b.byusers,b.CODE,d.endtime AS sub_endtime,a.overdue_m_status,a.id,a.order_id,a.user_id,a. STATUS, a.amount, a.crtime, a.endtime,a.loan_day,a.loan_time, a.loan_amount, a.stages, a.lastuser_id,a.lastuser_name,a.loan_user FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id ORDER BY d.endtime ASC,a.loan_time DESC,a.id DESC ) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC limit '.$page->firstRow . ',' . $page->listRows;
        $list=$this->model->query($sql);
        $ids = [];
        $this->assign($for_total);
        foreach($list as $v) {
            if(empty( $v[$str] )) {
                continue;
            }
            $ids[$v[$str]] = $v[$str];
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 逾期用户详情
     */
    function overdue_info()
    {
        $this->repayment( 1 );
    }

    /*
     * 逾期审核
     */
    function overdue_exam()
    {
        $RoleUser = new RoleUser();
        $list = $RoleUser->getDaiHouList();
        $this->assign('daihou',$list);
        //查看这个订单是否有逾期记录，如果有才继续走下去，否则error
        $id = I( 'get.id', 0 );//订单表主键ID
        //查一下这行记录的status
        $status = $this->model->where(['id'=>$id])->getField('status');
        if(empty($status) || $status!=3){
            $this->error("该订单未逾期");
        }
        $this->repayment( 2 );
    }

    /**
     * 催收后记
     */
        public function after_collection(){
        //$request_method = $_SERVER['REQUEST_METHOD'];
        $data = I( 'post.options', 0 );
        if(empty($data)){
            $RoleUser = new RoleUser();
            $list = $RoleUser->getDaiHouList();
            $this->assign('daihou',$list);
            //获取催收记录
            $order_id = I('id',0);
            //查一下这行记录的status
            $status = $this->model->where(['id'=>$order_id])->getField('status');
            if(empty($status) || $status!=3){
                $this->error("该订单未逾期");
            }
            $cs_where['order_id'] = $order_id;
            $group = get_groups_admin_user();
            if($group=='11'){
                $cs_where['createby']=get_current_admin_id();
            }
            $this->cs_list = M('after_collection','system_',C('DB_CONFIG2'))->where($cs_where)->select();
            //获取逾期状态操作记录
            $overdue_where['order_id'] = $order_id;
            $this->overdue_record = M('overdue_record','system_',C('DB_CONFIG2'))->where($overdue_where)->select();
            $collection_type=M( "collection_type", 'system_', C( 'DB_CONFIG2' ) )->field('id,name')->where(['is_true'=>'1'])->select();
            $this->assign( 'collection_type', $collection_type);
            $this->repayment( 2 );
        }else{
            if(empty( $data )) {
                $this->error( '数据传入失败！' );
            }
            $order_id = $data['id'];
            $admin_id = get_current_admin_id();//登录管理员ID
            $c_data['create_time'] = time();
            $c_data['createby'] = $admin_id;
            $c_data['collection_note'] = $data['collection_note'];
            $c_data['order_id'] = $order_id;
            $res = M( "after_collection", 'system_', C( 'DB_CONFIG2' ) )->add( $c_data );
            if(!empty($data['collection_type']) && !empty($data['user_id']) ){
                if(in_array('-1',$data['collection_type'])){
                    $data['collection_type']=null;
                }else{
                    $data['collection_type']=implode(',',$data['collection_type']);
                }
                M( "user", 'system_', C( 'DB_CONFIG2' ) )->where(['id'=>$data['user_id']])->save(['collection_type'=>$data['collection_type']]);
            }
            if($res){
                //$this->success( "添加催收记录成功！", U( "Examine/loan_overdue" ) );
                $this->success( "添加催收记录成功！<script>window.history.go(-1);</script>");
            }else{
                $this->error('添加催收记录失败');
            }
        }
    }

    //逾期还款 - 提交
    function overdue_exam_act()
    {
        $data = I( 'post.options', 0 );
        //pp($data);die;
        //Array(    [id] => 313    [user_id] => 14    [stages] => 1    [message] =>     [exam_amount] => 1200    [wechat_amount] =>     [alipay_amount] =>     [bank_amount] => )
        if(empty( $data ) || $data['exam_amount'] < 0 || !is_numeric( $data['exam_amount'] )) {
            $this->error( '数据传入失败！' );
        }
        if($data['payee']==null){
            $this->error("请选择收款人员");
        }
        //从子订单中查出该用户订单的总逾期本金
        $sum = $this->sub_model
            ->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )
            ->sum( 'amount' );//逾期记录的本金总金额
        $sta = $this->model->where( [ 'id' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )->field( 'stages' )->find();//从该逾期订单中查出它分期数有多少期
        $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->find();//查出用户借贷和余额信息
        if($yue['deposit'] > 0) {//余额还款
            $this->error( '余额不为0,不能人工逾期还款!' );
        }
        $dt = yu_amount( $data['user_id'], true );//用户待还的逾期费和每期待还逾期费
        $dt['all'] = $dt['all'] < 0 ? 0 : $dt['all'];
        //逾期应还本金+总逾期费用，如果小于填入的实收，则说明实收填多了
        if(($sum + $dt['all']) < $data['exam_amount']) {
            $this->error( '请输入正确的金额！' );
        }
        $admin_id = get_current_admin_id();//登录管理员ID
        $data['message'] = empty( $data['message'] ) ? '借款还款' : $data['message'];
        //如果收到的实收金额为非正数，则就不行了
        if($data['exam_amount'] <= 0) {
            $message_log = [
                'user_id' => $data['id'],
                'examine_id' => $admin_id,
                'message' => $data['message'],
                'status' => 1,
                'types' => 4,
                'amount' => 0,
                'stages' => $data['stages'],
                'deposit' => 0,
                'payee' => $data['payee'],
            ];
            M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $message_log );
            $this->success( "审核备注成功！", U( "Examine/loan_overdue" ) );
        }
        $message_log = [];
        //增加一个专门的三个实收
        $message_log[] = [
            'user_id' => $data['id'],
            'examine_id' => $admin_id,
            'message' => '三个实收',
            'status' => 1,
            'types' => 4,
            'amount' => 0,
            'stages' => $data['stages'],
            'deposit' => 0,
            'wechat_amount'=>$data['wechat_amount'],
            'alipay_amount'=>$data['alipay_amount'],
            'bank_amount'=>$data['bank_amount'],
            'real_amount'=>$data['real_amount'],
            'overdue_amount'=>$data['overdue_amount'],
            'payee'=>$data['payee'],
        ];
        $message_log[] = [
            'user_id' => $data['user_id'],
            'examine_id' => $admin_id,
            'message' => '人工充值',
            'status' => 1,
            'types' => 0,
            'amount' => $data['exam_amount'],
            'stages' => $data['stages'],
            'deposit' => $data['exam_amount'],
            'wechat_amount' => '',
            'alipay_amount' => '',
            'bank_amount' => '',
            'real_amount'=>'',
            'overdue_amount'=>'',
            'payee'=>$data['payee'],
        ];
        //set_log($data['user_id'],0,1,'人工充值','chong',$data['id'],$data['exam_amount'],'','',$data['stages']);
        if($dt['all'] > 0) {//还逾期
            $yuqifei = $data['exam_amount'] > $dt['all'] ? $dt['all'] : $data['exam_amount'];
            $message_log[] = [
                'user_id' => $data['user_id'],
                'examine_id' => $admin_id,
                'message' => '人工逾期还款',
                'status' => 1,
                'types' => 0,
                'amount' => $yuqifei,
                'stages' => $data['stages'],
                'deposit' => abs($data['exam_amount']-$dt['all']),
                'wechat_amount' => '',
                'alipay_amount' => '',
                'bank_amount' => '',
                'real_amount'=>'',
                'overdue_amount'=>'',
                'payee'=>$data['payee'],
            ];
            $amoun = $data['exam_amount'];//实收
            //遍历将每期逾期的记录要还多少钱放进去
            foreach($dt['list'] as $k => $v) {
                $amoun = $amoun - $v;//实收累减
                if($amoun < 0 || $amoun == 0) {//逾期还部分
                    $message_log[] = [
                        'user_id' => $data['id'],
                        'examine_id' => $admin_id,
                        'message' => '逾期还款'.' '.$data['message'],
                        'status' => 1,
                        'types' => 5,
                        'amount' => $v + $amoun,//该期应还的逾期费用-不够的实收 = 这次交的逾期费用
                        'stages' => $k,
                        'deposit' => 0,//这个时候余额肯定是0
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                    break;//如果实收钱花了一次没有剩余或者还不够，直接退出
                } else {
                    $message_log[] = [
                        'user_id' => $data['id'],
                        'examine_id' => $admin_id,
                        'message' => '逾期还款',' '.$data['message'],
                        'status' => 1,
                        'types' => 5,
                        'amount' => $v,
                        'stages' => $k,
                        'deposit' => 0,//FIXME:这里不一定是0
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                }
            }
        }
        //判断驶入实收大于总逾期金额，则做抵消处理
        if(($data['exam_amount'] - $dt['all']) > 0) {//若实收还逾期充足
            $other = $data['exam_amount'] - $dt['all'];//还完剩余的实收钱
            //已还金额
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ))->where( [ 'user_id' => $data['id'] ] )->where( 'types in (4,7)' )->field( 'sum(amount) as amount,stages' )->group( 'stages' )->select();//查出每期已还的本金
            if($sta['stages'] == 1) {//如果只有1期
                $logs = 0;//累加该期的所有的已还本金
                foreach($log as $v) {
                    $logs += $v['amount'];
                }
            } else {
                $logs = 0;//
                $logs_array = [];
                $sub_order = $this->sub_model->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )->order( 'id asc' )->select();//查出子订单中的逾期的记录
                $stages = [];
                foreach($sub_order as $v) {
                    $stages[] = substr( $v['stages'], 0, 1 );//组装期数
                }
                //$log为每期已还本金
                foreach($log as $v) {
                    $n = substr( $v['stages'], 0, 1 );//期数
                    if(!in_array( $n, $stages )) {
                        continue;//排除错误期数
                    }
                    if(empty( $logs_array[$n] )) {
                        $logs_array[$n] = 0;//每期累加从0开始
                    }
                    $logs += $v['amount'];//每期逾期的本金费用累加
                    $logs_array[$n] += $v['amount'];//每期的逾期本金
                }
            }
            //$sum是订单总逾期本金(orders_sub总的status=3的amount)，$other是扣掉逾期费用的剩余实收，$logs是已还的本金
            if($sum == ($other + $logs)) {//全清
                $message_log[] = [
                    'user_id' => $data['id'],
                    'examine_id' => $admin_id,
                    'message' => $data['message'],
                    'status' => 1,
                    'types' => 4,
                    'amount' => $sum - $logs,
                    'stages' => 1,
                    'deposit' => 0,
                    'wechat_amount' => '',
                    'alipay_amount' => '',
                    'bank_amount' => '',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工还款',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $sum - $logs,
                    'stages' => $data['stages'],
                    'deposit' => 0,
                    'wechat_amount' => '',
                    'alipay_amount' => '',
                    'bank_amount' => '',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];
                $status = [ 'status' => 2 ];
                if($ts = I( 'get.disp', 0 )) {
                    $status['is_third'] = get_current_admin_id();
                }
                $this->sub_model->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )->save( [ 'status' => 2 ] );//全清的话可以所有order_sub的状态都为2
                //放在下面统一计算
                //M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->save(array('late_amount'=>($yue['late_amount']-$sum - $logs)>0?($yue['late_amount']-$sum - $logs):0));
                //查询未还款的子订单和对应状态
                $sub_or=$this->sub_model
                    ->field('id,status')->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'] ] )->where('status in (1,3,4)')->select();
                if(empty($sub_or)){
                    M( "user", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $data['user_id'] ] )->save( [ 'renew' => '1', 'type_borr' => 1 ] );
                    $url = $this->jum_url . "?app_act=index/wechat_r_f";
                    $post_data = [
                        'id' => $data['user_id'],
                        'amount' => '',
                        'type' => 3,
                        'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['user_id'] ),
                    ];
                    A( 'indexlinks' )->http_post( $url, $post_data );
                }else{
                    foreach($sub_or as $v){
                        if($v['status']==4 && $status['status']!=3){
                            $status['status'] = 4 ;
                        }else{
                            $status['status']=$v['status'];
                        }
                        if($status['status']==3){
                            break;
                        }
                    }
                }
                $this->model->where( [ 'id' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )->save( $status );
            } else {
                if($sta['stages'] == 1) {
                    $message_log[] = [
                        'user_id' => $data['id'],
                        'examine_id' => $admin_id,
                        'message' => $data['message'],
                        'status' => 1,
                        'types' => 4,
                        'amount' => $other,
                        'stages' => $data['stages'],
                        'deposit' => 0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                    $message_log[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 0,
                        'amount' => $other,
                        'stages' => $data['stages'],
                        'deposit' => 0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                } else {
                    $message_log[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 0,
                        'amount' => $other,
                        'stages' => 1,
                        'deposit' => 0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                    if(!isset($sub_order)){
                        $sub_order = $this->sub_model->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3 ] )->order( 'id asc' )->select();//查出子订单中的逾期的记录
                    }
                    foreach($sub_order as $v) {
                        $n = substr( $v['stages'], 0, 1 );//期数
                        if(empty( $logs_array[$n] )) {
                            $logs_array[$n] = 0;
                        }
                        if(($v['amount'] - $logs_array[$n]) > $other) {
                            $message_log[] = [
                                'user_id' => $data['id'],
                                'examine_id' => $admin_id,
                                'message' => $data['message'],
                                'status' => 1,
                                'types' => 4,
                                'amount' => $other,
                                'stages' => $v['stages'],
                                'deposit' => 0,
                                'wechat_amount' => '',
                                'alipay_amount' => '',
                                'bank_amount' => '',
                                'real_amount'=>'',
                                'overdue_amount'=>'',
                                'payee'=>$data['payee'],
                            ];//只能还一期的情况
                            break;
                        } else if(($v['amount'] - $logs_array[$n]) == $other) {
                            $message_log[] = [
                                'user_id' => $data['id'],
                                'examine_id' => $admin_id,
                                'message' => $data['message'],
                                'status' => 1,
                                'types' => 4,
                                'amount' => $other,
                                'stages' => $v['stages'],
                                'deposit' => 0,
                                'wechat_amount' => '',
                                'alipay_amount' => '',
                                'bank_amount' => '',
                                'real_amount'=>'',
                                'overdue_amount'=>'',
                                'payee'=>$data['payee'],
                            ];
                            $this->sub_model->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3, 'id' => $v['id'] ] )->save( [ 'status' => 2 ] );
                            break;
                        } else {
                            $message_log[] = [
                                'user_id' => $data['id'],
                                'examine_id' => $admin_id,
                                'message' => $data['message'],
                                'status' => 1,
                                'types' => 4,
                                'amount' => $v['amount'] - $logs_array[$n],
                                'stages' => $v['stages'],
                                'deposit' => 0,
                                'wechat_amount' => '',
                                'alipay_amount' => '',
                                'bank_amount' => '',
                                'real_amount'=>'',
                                'overdue_amount'=>'',
                                'payee'=>$data['payee'],
                            ];
                            $other = $other - ($v['amount'] - $logs_array[$n]);
                            $this->sub_model->where( [ 'pid' => $data['id'], 'user_id' => $data['user_id'], 'status' => 3, 'id' => $v['id'] ] )->save( [ 'status' => 2 ] );
                        }
                    }
                }
            }
        }
        //用户待还和余额没改到
        M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $message_log );
        //更改待还
        $hasIncome = M( "log", 'system_', C( 'DB_CONFIG2' ))->where( [ 'user_id' => $data['id'] ] )->where( 'types in (4,7)' )->field( 'ifnull(sum(amount),0.00) as income' )->find();
        //该订单总的要还的
        $should = M('ders','or',C( 'DB_CONFIG2' ))->where(['id'=>$data['id']])->getField('amount');
        $user_late_amount = $should-$hasIncome['income'];//应还-已还 = 待还
        M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->save([
            'late_amount'=>$user_late_amount>0?$user_late_amount:0
        ]);//计算待还
        //$this->success( "审核成功！", U("Examine/loan_overdue" ));
        $this->success( "审核成功！<script>window.history.go(-1);</script>");
    }

    /*
     * 逾期续期
     */
    public function overdue_renwal()
    {
        $id = I( 'get.id', 0 );
        if(empty( $id )) {
            $this->error( '数据传入失败！' );
        }
        //查看这笔订单是否有未审核的续期记录，如果有，必须要先审完上笔续期记录才能继续续期
        $renewalCount = M('renewal','orders_',C('DB_CONFIG2'))->where(['status'=>0,'oid'=>$id])->count();
        if($renewalCount>0){
            $this->error( '该笔订单有未审核的续期记录，不能重复申请！' );
        }
        //查看这个订单是否有逾期记录，如果有才继续走下去，否则error
        $status = $this->model->where(['id'=>$id])->getField('status');//查一下这行记录的status
        if(empty($status) || $status!=3){
            $this->error("该订单未逾期");
        }
        $result = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->where( [ "a.id" => $id ] )
            ->field( 'b.bank,b.silver_card,b.silver_number,b.account_status,b.name,b.mobile,a.*' )->find();
        //$yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['user_id'] ] )->find();
        //if($yue['deposit'] > 0) {//余额还款
        //    $this->error( '余额不为0,不能人工逾期续期!' );
        //}
        $yue = (new WareHouse())->getWareHouse($result['user_id']);
        $result['deposit'] = $yue['deposit'];
        $where = [
            'pid' => $id,
            'user_id' => $result['user_id'],
        ];
        $sub = $this->sub_model->where( $where )->order( "id asc" )->select();
        //取出最小的逾期子订单ID（分期数最小的订单ID）
        $yu_sub = [];
        foreach($sub as $v){
            if($v['status'] == 3){
                $stages = substr($v['stages'],0,1);
                $yu_sub[] = ['id'=>$v['id'],'stages'=>$stages];
            }
        }
        array_multisort(array_column($yu_sub,'stages'),SORT_ASC,$yu_sub);//用分期数排序
        //取第一个（最小分期的逾期订单ID）
        $min_yu_id = $yu_sub[0]['id'];
        $this->assign('min_yu_id',$min_yu_id);
        $renewal = $this->renewal_model
            ->where( [ 'order_id' => $result['order_id'], 'oid' => $result['id'], 'user_id' => $result['user_id'] ] )
            ->order( "crtime asc" )->select();
        $ids = [];
        $results = M( "log", 'system_', C( 'DB_CONFIG2' ) )
            ->where( [ "user_id" => $result['id'] ] )
            ->where( 'types in (1,3,4,5,7)' )
            ->order('id desc')
            ->select();
        foreach($results as $v) {
            if(empty( $v )) {
                continue;
            }
            $ids[$v['examine_id']] = $v['examine_id'];
            $ids[$v['payee']] = $v['payee'];//将收款人装起来
        }
        $this->assign( 'logs', $results );

        foreach($renewal as $v) {
            if(empty( $v )) {
                continue;
            }
            $ids[$v['lastuser_id']] = $v['lastuser_id'];
        }
        if(!empty( $ids )) {
            $lastuser = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $lastusers = [];
            foreach($lastuser as $v) {
                $lastusers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'lastuser', $lastusers );
        }
        $RoleUser = new RoleUser();
        $list = $RoleUser->getDaiHouList();//贷后人员列表
        $this->assign('daihou',$list);
        $this->assign( 'renewal', $renewal );
        $this->assign( 'order', $result );
        $this->assign( 'sub', $sub );
        $this->assign('yu_amount',yu_amount($result['user_id'],true));
        $this->display();
    }

    /*
     *后台逾期续期操作
     */
    function overdue_renwal_act()
    {
        $data = $option = I( 'post.options', 0 );
        //print_r($data);
        //die;

        if(empty( $data['id'] ) || empty( $data['user_id'] )) {
            $this->error( '数据传入失败！' );
        }
        if($data['payee'] == null){//检查是否选了贷后人员下拉菜单
            $this->error('请选择收款人员');
        }
        $times = date( 'Y-m-d' );
        $where = [ "id" => $data['id'], "user_id" => $data['user_id'] ];
        $result = $this->model->where( $where )->find();
        $yue = (new WareHouse())->getWareHouse($data['user_id']);
        if($yue['deposit']<0){
            $this->error('用户余额有误，请检查');
        }
        //fixme:增加后面计算第几期和分期的
        if($result['stages'] == 1) {
            $sub = $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'id' => $data['status'] ] )->field( 'stages' )->find();
            $stage = 1;
            $sub['stages'] += 1;
            $num = 1;
            $nums = $sub['stages'];
        } else {
            $sub = $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'id' => $data['status'] ] )->field( 'stages' )->find();
            $stage = substr( $sub['stages'], 0, 1 );
            $num = substr( $sub['stages'], 0, 1 );
            $nums = substr( $sub['stages'], 1 ) + 1;
        }
        //计算续期金额 和续期后的到期日期
        $rollover = (new Amount())->calOverdueFeesAndDays($result,$data['orther_time']);
        $data['orther_amount'] = $rollover['orther_amount'];//续期金额
        $data['orther_time'] = $rollover['orther_time'];//续期后到期日期
        if(isset($data['is_pay_yu']) && $data['is_pay_yu'] == 0){
            $dts = yu_amount( $data['user_id'], true ,array_values($data['cancel_yu']));//用户逾期费用详情
        }else{
            $dts = yu_amount( $data['user_id'], true );//用户逾期费用详情
        }

        $dts['all'] = empty( $dts['all'] ) ? 0 : $dts['all'];
        $message_log = [];
        $admin_id = get_current_admin_id();
        //增加一个专门的三个实收
        $message_log[] = [
            'user_id' => $data['id'],
            'examine_id' => $admin_id,
            'message' => '三个实收',
            'status' => 1,
            'types' => 3,
            'amount' => 0,
            'stages' => $sub['stages'],
            'deposit' => 0,
            'wechat_amount'=>$data['wechat_amount'],
            'alipay_amount'=>$data['alipay_amount'],
            'bank_amount'=>$data['bank_amount'],
            'real_amount'=>'',
            'overdue_amount'=>$data['overdue_amount'],
            'payee'=>$data['payee'],
        ];
        //查询用于是否有余额
        //dd($yue);die;
        if($yue['deposit']>0){
            $spare_money = $yue['deposit']-$dts['all']-$data['orther_amount'];
            if($spare_money>=0){//余额充足，不用人工充值
                $deposit = $yue['deposit'];//用来累减
                if($dts['all'] > 0) {//逾期还款
                    $message_log[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '逾期还款',
                        'status' => 1,
                        'types' => 0,
                        'amount' => $dts['all'],
                        'stages' => 0,
                        'deposit' => $yue['deposit']-$dts['all'],
                        'wechat_amount'=>'',
                        'alipay_amount'=>'',
                        'bank_amount'=>'',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                    foreach($dts['list'] as $k => $v) {
                        $message_log[] = [
                            'user_id' => $data['id'],
                            'examine_id' => $admin_id,
                            'message' => '逾期还款',
                            'status' => 1,
                            'types' => 5,
                            'amount' => $v,
                            'stages' => $k,
                            'deposit' => 0,//给系统看的一直都是0
                            'wechat_amount'=>'',
                            'alipay_amount'=>'',
                            'bank_amount'=>'',
                            'real_amount'=>'',
                            'overdue_amount'=>'',
                            'payee'=>$data['payee'],
                        ];
                        $deposit -= $v;//余额累减
                    }
                }
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => $result['order_id'] . '续' . $stage . '期',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $data['orther_amount'],
                    'stages' => 0,
                    'deposit' => $spare_money,//剩余的余额>=0
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];
                $new_deposit = $spare_money;//用户新余额，用来更新用户余额
            }else{//不够，要充值
                $recharge_money = abs($spare_money);//要充值的钱
                $deposit = $recharge_money + $yue['deposit'];//充值之后的钱
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工充值',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $recharge_money,
                    'stages' => 0,
                    'deposit' => $deposit,
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];//充值
                if($dts['all'] > 0) {//逾期还款
                    $message_log[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '逾期还款',
                        'status' => 1,
                        'types' => 0,
                        'amount' => $dts['all'],
                        'stages' => 0,
                        'deposit' => $deposit-$dts['all'],
                        'wechat_amount'=>'',
                        'alipay_amount'=>'',
                        'bank_amount'=>'',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                    foreach($dts['list'] as $k => $v) {
                        $message_log[] = [
                            'user_id' => $data['id'],
                            'examine_id' => $admin_id,
                            'message' => '逾期还款',
                            'status' => 1,
                            'types' => 5,
                            'amount' => $v,
                            'stages' => $k,
                            'deposit' => 0,//给系统看的一直都是0
                            'wechat_amount'=>'',
                            'alipay_amount'=>'',
                            'bank_amount'=>'',
                            'real_amount'=>'',
                            'overdue_amount'=>'',
                            'payee'=>$data['payee'],
                        ];
                        $deposit -= $v;//余额累减
                    }
                }
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => $result['order_id'] . '续' . $stage . '期',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $data['orther_amount'],
                    'stages' => 0,
                    'deposit' => $deposit- $data['orther_amount'],//用完了之后这里肯定为0
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];
                $deposit -= $data['orther_amount'];//剩下的余额继续累减
                $new_deposit = $deposit;//用户新余额，用来更新用户余额
            }
        }else{
            $message_log[] = [
                'user_id' => $data['user_id'],
                'examine_id' => $admin_id,
                'message' => '人工充值',
                'status' => 1,
                'types' => 0,
                'amount' => $data['orther_amount'] + $dts['all'],
                'stages' => 0,
                'deposit' => $data['orther_amount'] + $dts['all'],
                'wechat_amount'=>'',
                'alipay_amount'=>'',
                'bank_amount'=>'',
                'real_amount'=>'',
                'overdue_amount'=>'',
                'payee'=>$data['payee'],
            ];//充值
            if($dts['all'] > 0) {//逾期还款
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '逾期还款',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $dts['all'],
                    'stages' => 0,
                    'deposit' => $data['orther_amount'],
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>$data['payee'],
                ];
                foreach($dts['list'] as $k => $v) {
                    $message_log[] = [
                        'user_id' => $data['id'],
                        'examine_id' => $admin_id,
                        'message' => '逾期还款',
                        'status' => 1,
                        'types' => 5,
                        //'amount' => $dts['all'],
                        'amount' => $v,
                        'stages' => $k,
                        'deposit' => 0,//给系统看的一直都是0
                        'wechat_amount'=>'',
                        'alipay_amount'=>'',
                        'bank_amount'=>'',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>$data['payee'],
                    ];
                }
            }
            $message_log[] = [
                'user_id' => $data['user_id'],
                'examine_id' => $admin_id,
                'message' => $result['order_id'] . '续' . $stage . '期',
                'status' => 1,
                'types' => 0,
                'amount' => $data['orther_amount'],
                'stages' => 0,
                'deposit' => 0,
                'wechat_amount'=>'',
                'alipay_amount'=>'',
                'bank_amount'=>'',
                'real_amount'=>'',
                'overdue_amount'=>'',
                'payee'=>$data['payee'],
            ];
            $new_deposit = 0;//用户新余额，用来更新用户余额
        }
        //最后一波公共的
        $message_log[] = [
            'user_id' => $data['id'],
            'examine_id' => $admin_id,
            'message' => '人工审核续期 ' . $data['message'],
            'status' => 1,
            'types' => 3,
            'amount' => $data['orther_amount'],
            'stages' => $sub['stages'],
            'deposit' => 0,
            'wechat_amount'=>'',
            'alipay_amount'=>'',
            'bank_amount'=>'',
            'real_amount'=>'',
            'overdue_amount'=>'',
            'payee'=>$data['payee'],
        ];

        //判断是否有工作人员的延迟操作，【不收逾期费时才触发】（如，用户昨天收到款，今天才操作续期）
        if($option['is_pay_yu'] == 0){
            $data['orther_time'] = date("Y-m-d",strtotime($data['orther_time']." -".intval($option['late_yu_days'])." day"));
        }
        //如果续期到的日期刚好是今天，那么状态变成已到期
        if($data['orther_time'] == date('Y-m-d')){
            $dt = [
                'endtime' => $data['orther_time'],
                'status' => 4,
            ];
        }else{
            $dt = [
                'endtime' => $data['orther_time'],
                'status' => 1,
            ];
        }

        if($result['stages'] == 1) {
            $dt['stages'] = $sub['stages'] + 1;
        } else {
            $dt['stages'] = substr( $sub['stages'], 0, 1 ) . (substr( $sub['stages'], 1 ) + 1);
        }

        //保存子订单
        $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'id' => $data['status'] ] )->save( $dt );

        $sub_order = $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'] ] )->select();
        $sta = [
            'status' => 1,
        ];
        foreach($sub_order as $v) {
            if($v['status'] == 3) {
                $sta['status'] = 3;
                break;
            }
            if($v['status'] == 4) {
                $sta['status'] = 4;
            }
        }

        if($data['orther_time'] > $result['endtime']) {
            $sta['endtime'] = $data['orther_time'];
        }
        $this->model->where( $where )->save( $sta );
        $sts = '第' . $num . '期' . $nums . '次续期';

        $dts = [
            'amount' => $data['orther_amount'],
            'endtime' => $data['orther_time'],
            'renewal' => $sts.' 还款时间 ' . $times . ' 续期到 ' . $data['orther_time'],
            'user_id' => $data['user_id'],
            'oid' => $data['id'],
            'order_id' => $result['order_id'],
            'lastuser_id' => $admin_id,
            'status' => 1,
            'stages' => $sub['stages'],
        ];
        $this->renewal_model->add( $dts );
        M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $message_log );
        (new WareHouse())->where(['user_id'=>$result['user_id']])->save(['deposit'=>$new_deposit]);//更改用户余额
        $url = $this->jum_url . "?app_act=index/wechat_r_f";
        $post_data = [
            'id' => $data['user_id'],
            'amount' => '',
            'type' => 4,
            'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['user_id'] ),
        ];
        A( 'indexlinks' )->http_post( $url, $post_data );
        //$this->success( "审核成功！", U( "Examine/loan_overdue" ) );
        $this->success( "审核成功！<script>window.history.go(-1);</script>");
    }

    /*
     * 借款 详情
     * ① 已到期还款表单页面
     * ② 未到期提前还款表单页面
     * ③ 逾期还款
     * ...
     */
    function repayment($get_user = 0)
    {
        $id = I( 'get.id', 0 );//订单表主键ID
        if($id) {
            //$this->model模型为order表模型
            $result = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( [ "a.id" => $id ] )
                ->field( 'b.collection_type,b.bank,b.silver_card,b.silver_number,b.account_status,b.name,b.mobile,b.photos_url,a.*' )->find();//将原订单查出来

            $where = [
                'pid' => $id,
                'user_id' => $result['user_id'],
            ];
            $sub = $this->sub_model->where($where)->order( "id asc" )->select();//将订单分期查出来，对应order_sub表
            //取出最小的非还款完成的订单ID
            $yu_sub = [];
            foreach($sub as $v){
                if($v['status'] != 2){
                    $stages = substr($v['stages'],0,1);
                    $yu_sub[] = ['id'=>$v['id'],'stages'=>$stages];
                }
            }
            array_multisort(array_column($yu_sub,'stages'),SORT_ASC,$yu_sub);//用分期数排序
            //取第一个（最小分期的逾期订单ID）
            $min_yu_id = $yu_sub[0]['id'];
            $this->assign('min_yu_id',$min_yu_id);

            $renewal = $this->renewal_model
                ->where( [ 'order_id' => $result['order_id'], 'oid' => $result['id'], 'user_id' => $result['user_id'] ] )
                ->order( "crtime desc,id desc" )->select();//将该订单的续期记录查出来
            $ids = [];
            switch($get_user) {
                case 1://用户信息
                    $results = $this->user_model->join( "LEFT JOIN attachment a on system_user.silver_photo=a.id and system_user.id=a.user_id" )
                        ->where( [ "system_user.id" => $result['user_id'] ] )
                        ->field( 'a.url,system_user.*' )->find();
                    $bank = M( "bank", 'system_', C( 'DB_CONFIG2' ) )->select();
                    $education = M( "education", 'system_', C( 'DB_CONFIG2' ) )->select();
                    $this->assign( 'user', $results );
                    $this->assign( 'bank', $bank );
                    $this->assign( 'education', $education );
                    $mobile_list = A( 'indexadmin' )->get_user_mobile_list( $result['user_id'], true );
                    $this->assign( 'mobile_list', $mobile_list['list'] );
                    $this->assign( 'page', $mobile_list['page'] );
                    //rong360报告的西瓜分
                    $decision = M('user_report360','system_',C( 'DB_CONFIG2' ))->where(['user_id'=>$result['id']])->getField('decision_score');
                    $this->assign( 'decision', $decision);
                    break;
            }
            //types解释：
            //0用户审核1订单审核2用户信息审核3续期审核4逾期多出还款记录5逾期还款记录6订单初审7用户申请还款8运营商填写记录9推广记录
            $resul = M( "log", 'system_', C( 'DB_CONFIG2' ) )
                ->where( [ "user_id" => $result['id'] ] )
                //->where( 'types in (1,4,5,6,7)' )
                ->where( 'types in (1,3,4,5,6,7)' )
                ->order( 'crtime desc,id desc' )
                ->select();//用户资金明细记录表，查询该用户的
            foreach($resul as $v) {
                //如何$v为空或者审核人为0（未审核），则跳过
                if(empty( $v ) || $v['examine_id'] == 0) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];//将审核人装进来
                $ids[$v['payee']] = $v['payee'];//将收款人装起来
            }
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'types' => '2', 'user_id' => $result['user_id'] ] )->select();//将用户信息审核记录查出来
            //处理用户信息审核记录
            foreach($log as $v) {
                $ids[$v['examine_id']] = $v['examine_id']; //将用户信息审核审核人装起来
                $ids[$v['payee']] = $v['payee'];//将收款人装起来
            }
            //处理续期记录
            foreach($renewal as $v) {
                if(empty( $v['lastuser_id'] )) {
                    continue;
                }
                $ids[$v['lastuser_id']] = $v['lastuser_id'];//将续期审核人装起来
            }
            if(!empty( $ids )) {
                $lastuser = M( 'users' )->field( 'id,user_login' )->select();//将审核人的后台用户ID和用户名查出
                $lastusers = [];
                foreach($lastuser as $v) {
                    $lastusers[$v['id']] = $v['user_login'];
                }
                $this->assign( 'lastuser', $lastusers );
            }
            //result是上面查询的order表的一条记录
            $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['user_id'] ] )->find();//查询该订单下的该用户的余额
            //保证金
            $result['bond']=M( "order_bond", 'system_', C( 'DB_CONFIG2' ) )->field('bond_amount,is_back')->where( [ 'user_id' => $result['user_id'],'order_id'=>$result['id']] )->find();
            $result['deposit'] = $yue['deposit'];
            $this->assign( 'log', $log );//将用户信息审核记录查出来
            $this->assign( 'logs', $resul );//用户资金明细记录表，查询该用户的
            $this->assign( 'renewal', $renewal );//用户续期记录
            $this->assign( 'order', $result );//订单记录及用户资金情况
            $this->assign( 'sub', $sub );//订单分期记录
            $this->display();
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 续期申请
     */
    function renwal()
    {
        $id = I( 'get.id', 0 );//订单表主键ID
        //查看这笔订单是否有未审核的续期记录，如果有，必须要先审完上笔续期记录才能继续续期
        $renewalCount = M('renewal','orders_',C('DB_CONFIG2'))->where(['status'=>0,'oid'=>$id])->count();
        if($renewalCount>0){
            $this->error( '该笔订单有未审核的续期记录，不能重复申请！' );
        }
        $this->repayment();
    }

    /*
     * 已到期的续期审核
     */
    function renwal_act()
    {
        $data = I( 'post.options', 0 );
        if(empty( $data['id'] ) || empty( $data['user_id'] )) {
            $this->error( '数据传入失败！' );
        }
        $where = [ "id" => $data['id'], "user_id" => $data['user_id'], 'status' => 4 ];
        $result = $this->model
            ->where( $where )
            ->find();
        if(empty( $result )) {
            $this->error( '请刷新重试,该借款已处理!' );
        }
        $amount = xu_amount(array($result));
        $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['user_id'] ] )->find();
        switch($data['orther_time']) {
            case '1':
                $data['orther_amount'] = $amount['renewal_fee'];
                $data['orther_time'] = date( 'Y-m-d', strtotime( '+1days' ) );
                break;
            case '2':
                $data['orther_amount'] = $amount['renewal_fee'] * 2;
                $data['orther_time'] = date( 'Y-m-d', strtotime( '+2days' ) );
                break;
            case '6':
                $data['orther_amount'] = $amount['renewal_fee_sev'];//续期6天跟续期7天金额一样
                $data['orther_time'] = date( 'Y-m-d', strtotime( '+6days' ) );
                break;
            case '7':
                $data['orther_amount'] = $amount['renewal_fee_sev'];
                $data['orther_time'] = date( 'Y-m-d', strtotime( '+7days' ) );
                break;
            default:
                $this->error( '请选择正确的日期!' );
        }
        $message_log = [];
        $admin_id = get_current_admin_id();
        //增加一个专门的三个实收
        $message_log[] = [
            'user_id' => $data['id'],
            'examine_id' => $admin_id,
            'message' => '三个实收',
            'status' => 1,
            'types' => 3,
            'amount' => 0,
            'stages' => 0,
            'deposit' => 0,
            'wechat_amount'=>$data['wechat_amount'],
            'alipay_amount'=>$data['alipay_amount'],
            'bank_amount'=>$data['bank_amount'],
            'payee'=>get_current_admin_id(),
        ];
        if($result['stages'] == 1) {//单期
            $sub_order = $this->sub_model
                ->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'status' => '4' ] )->field( 'stages,status' )->find();
            if(empty( $sub_order )) {
                $this->error( '请刷新重试!' );
            }
            $dt = [
                'endtime' => $data['orther_time'],
                'status' => 1,
            ];
            $this->model->where( $where )->save( $dt );
            $dt['stages'] = $sub_order['stages'] + 1;
            $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'] ] )->save( $dt );
            $yue_amount = $yue['deposit'] - $data['orther_amount'];
            if($yue_amount < 0) {
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工充值',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $data['orther_amount'] - $yue['deposit'],
                    'stages' => 0,
                    'deposit' => $data['orther_amount'],
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
                $message_log[] = [
                    'user_id' => $data['id'],
                    'examine_id' => $admin_id,
                    'message' => '人工审核续期 ' . $data['message'],
                    'status' => 1,
                    'types' => 3,
                    'amount' => $yue_amount > 0 ? $data['orther_amount'] : ($data['orther_amount'] - $yue['deposit']),
                    'stages' => $sub_order['stages'],
                    'deposit' => 0,
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
            }
            $message_log[] = [
                'user_id' => $data['user_id'],
                'examine_id' => $admin_id,
                'message' => $result['order_id'] . '续期',
                'status' => 1,
                'types' => 0,
                'amount' => $data['orther_amount'],
                'stages' => 0,
                'deposit' => $yue_amount > 0 ? $yue_amount : 0,
                'wechat_amount'=>'',
                'alipay_amount'=>'',
                'bank_amount'=>'',
                'payee'=>get_current_admin_id(),
            ];

            if($yue['deposit'] > 0) {
                $message_log[] = [
                    'user_id' => $data['id'],
                    'examine_id' => 0,
                    'message' => '人工审核续期 ' . $data['message'],
                    'status' => 1,
                    'types' => 3,
                    'amount' => $yue_amount > 0 ? $data['orther_amount'] : $yue['deposit'],
                    'stages' => $sub_order['stages'],
                    'deposit' => 0,
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
            }
            $dts = [
                'amount' => $data['orther_amount'],
                'endtime' => $data['orther_time'],
                'renewal' => '还款时间 ' . $result['endtime'] . ' 续期到 ' . $data['orther_time'],
                'user_id' => $data['user_id'],
                'oid' => $data['id'],
                'order_id' => $result['order_id'],
                'lastuser_id' => $admin_id,
                'status' => '1',
                'stages' => $dt['stages'],
            ];
        } else {//多期
            $sub_order = $this->sub_model
                ->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'id' => $data['status'], 'status' => '4' ] )
                ->field( 'stages,status,endtime' )->find();
            if(empty( $sub_order )) {
                $this->error( '请刷新重试!' );
            }
            $or_order = $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'] ] )
                ->where( 'id!=' . $data['status'] )->field( 'stages,status' )->order( 'id asc' )->select();
            $status = 1;
            foreach($or_order as $v) {
                if($v['status'] == 2) {
                    continue;
                }
                $status = $status > $v['status'] ? $status : $v['status'];
            }
            $num = substr( $sub_order['stages'], 0, 1 );
            $dt = [
                'status' => $status,
            ];
            if($data['orther_time'] > $result['endtime']) {
                $dt['endtime'] = $data['orther_time'];
            }
            $this->model->where( $where )->save( $dt );
            $nums = (substr( $sub_order['stages'], 1 )) + 1;
            $dt['stages'] = $num . $nums;
            $dt['status'] = 1;
            $dt['endtime'] = $data['orther_time'];
            $this->sub_model->where( [ "pid" => $data['id'], "user_id" => $data['user_id'], 'id' => $data['status'] ] )->save( $dt );
            $nums = empty( $nums ) ? 1 : $nums;
            $sts = '第' . $num . '期' . $nums . '次续期';
            $yue_amount = $yue['deposit'] - $data['orther_amount'];
            if($yue_amount < 0) {
                $message_log[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工充值',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $data['orther_amount'] - $yue['deposit'],
                    'stages' => 0,
                    'deposit' => $data['orther_amount'],
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
                $message_log[] = [
                    'user_id' => $data['id'],
                    'examine_id' => $admin_id,
                    'message' => '人工审核续期 ' . $data['message'],
                    'status' => 1,
                    'types' => 3,
                    'amount' => $yue_amount > 0 ? $data['orther_amount'] : ($data['orther_amount'] - $yue['deposit']),
                    'stages' => $sub_order['stages'],
                    'deposit' => 0,
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
            }
            $message_log[] = [
                'user_id' => $data['user_id'],
                'examine_id' => $admin_id,
                'message' => $result['order_id'] . '续' . $num . '期',
                'status' => 1,
                'types' => 0,
                'amount' => $data['orther_amount'],
                'stages' => 0,
                'deposit' => $yue_amount > 0 ? $yue_amount : 0,
                'wechat_amount'=>'',
                'alipay_amount'=>'',
                'bank_amount'=>'',
                'payee'=>get_current_admin_id(),
            ];
            if($yue['deposit'] > 0) {//表示用户交的部分（要跟系统错开）
                $message_log[] = [
                    'user_id' => $data['id'],
                    'examine_id' => 0,
                    'message' => '人工审核续期 ' . $data['message'],
                    'status' => 1,
                    'types' => 3,
                    'amount' => $yue_amount > 0 ? $data['orther_amount'] : $yue['deposit'],
                    'stages' => $sub_order['stages'],
                    'deposit' => 0,
                    'wechat_amount'=>'',
                    'alipay_amount'=>'',
                    'bank_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
            }
            $dts = [
                'amount' => $data['orther_amount'],
                'endtime' => $data['orther_time'],
                'renewal' => $sts . ' 还款时间 ' . $sub_order['endtime'] . ' 续期到 ' . $data['orther_time'],
                'user_id' => $data['user_id'],
                'oid' => $data['id'],
                'order_id' => $result['order_id'],
                'lastuser_id' => $admin_id,
                'status' => '1',
                'stages' => $sub_order['stages'],
            ];
        }
        //余额清零
        M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['user_id'] ] )->save( [ 'deposit' => $yue_amount > 0 ? $yue_amount : 0 ] );
        $this->renewal_model->add( $dts );
        M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $message_log );
        $url = $this->jum_url . "?app_act=index/wechat_r_f";
        $post_data = [
            'id' => $data['user_id'],
            'amount' => '',
            'type' => 4,
            'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['user_id'] ),
        ];
        A( 'indexlinks' )->http_post( $url, $post_data );
        $this->success( "审核成功！", U( "Examine/loan_expire" ) );
    }

    /*
     * 未到期详情
     * 未到期提前还款页面
     */
    function nodue_info()
    {
        $this->repayment();
    }

    /*
     * 还款申请
     */
    function repayment_act()
    {
        $date = I( 'post.options' );
        $times = time();
        if(!empty( $date['id'] ) && !empty( $date['user_id'] )) {
            $order = $this->model->where( [ 'id' => $date['id'], 'user_id' => $date['user_id'] ] )
                ->field( 'loan_day,order_id,amount,stages,id,user_id' )
                ->find();
            $dt = [ 'status' => 8 ];
            $msg = '确认还款';
            $dt['endtime'] = date( 'Y-m-d', strtotime( '+' . $order['loan_day'] . ' days', $times ) );
//            set_log($date['id'],1,1,$msg);
//
//            $msg2='人工充值';
//            set_log($date['user_id'],0,1,$msg2,'chongs',$date['id']);
//
//            $msg2=$order['order_id'].'还款成功';
//            set_log($date['user_id'],0,1,$msg2,'kou',$date['id']);
//
//            //分期 子订单
//            $day=$order['loan_day']/$order['stages'];
//            $amount=$order['amount']/$order['stages'];
//            $times=date('Y-m-d',strtotime('+'.$day.' days',$times));
//            for($i=1;$i<=$order['stages'];$i++){
//                $times=date('Y-m-d',strtotime('+'.$day.' days',strtotime($times)));
//                $dts=array(
//                    'pid'=>$order['id'],
//                    'user_id'=>$order['user_id'],
//                    'stages'=>$i,
//                    'endtime'=>$times,
//                    'amount'=>$amount,
//                    'loan_day'=>$day,
//                );
//                $this->sub_model->add($dts);
//            }

            $this->model->where( [ 'id' => $date['id'] ] )->save( $dt );
            $this->success( "审核成功！", U( "Examine/index" ) );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 借款修改 审核已还款
     * ① 未到期提前还款审核 display=0
     * ② 已到期还款审核 display=1
     */
    function set_exam()
    {
        $data = I( 'post.options' );
       if(!empty( $data ) && !empty( $data['id'] ) && !empty( $data['user_id'] )) {
            $result = $this->model
                ->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )
                ->field( 'id,stages' )->find();//查找该订单记录
            if(empty( $result )) {
                $this->error( '数据传入失败！' );
            }
            //status数组中，0和1是前台传过来的是否选中已还款的状态，如果全部都是选的未还款，就不经过下述代码了（下属代码就要改状态等操作），直接审核成功（因为都未还款）,直接给他显示审核成功！）
            if(!in_array( '1', $data['status'] )) {
                if(empty($data['real_amount'])){
                    $add[] = [
                        'user_id' => $data['id'],
                        'examine_id' => get_current_admin_id(),
                        'message' => '人工审核还款 ' . $data['messgae'],
                        'status' => 1,
                        'types' => 1,
                        'stages' => $result['stages'],
                        'amount'=>0,
                        'deposit'=>0,
                        'wechat_amount'=>0,
                        'alipay_amount'=>0,
                        'bank_amount'=>0,
                        'real_amount'=>0,
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                }else{
                    if($result['stages']>1){
                        $this->error( '多期暂时不允许,部分还款！' );
                    }
                    $add[] = [
                        'user_id' => $data['id'],
                        'examine_id' => get_current_admin_id(),
                        'message' => '三个实收',
                        'status' => 1,
                        'types' => 4,
                        'stages' => $result['stages'],
                        'amount' => $data['real_amount'],
                        'deposit' => 0,
                        'wechat_amount'=>$data['wechat_amount'],
                        'alipay_amount'=>$data['alipay_amount'],
                        'bank_amount'=>$data['bank_amount'],
                        'real_amount'=>$data['real_amount'],
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $yue=M( "house", 'ware', C( 'DB_CONFIG2' ) )->field('late_amount,deposit')->where(['user_id'=>$data['user_id']])->find();
                    $add[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => get_current_admin_id(),
                        'message' => '人工还款 ',
                        'status' => 1,
                        'types' => 0,
                        'stages' => $result['stages'],
                        'amount'=>$data['real_amount'],
                        'deposit'=>($data['real_amount']-$yue['deposit'])>=0?0:($yue['deposit']-$data['real_amount']),
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $add[] = [
                        'user_id' => $data['id'],
                        'examine_id' => get_current_admin_id(),
                        'message' => '人工审核还款 ' . $data['messgae'],
                        'status' => 1,
                        'types' => 1,
                        'stages' => $result['stages'],
                        'amount'=>$data['real_amount'],
                        'deposit'=>0,
                        'wechat_amount'=>0,
                        'alipay_amount'=>0,
                        'bank_amount'=>0,
                        'real_amount'=>0,
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $up=[
                        'late_amount'=>($yue['late_amount']-$data['real_amount'])>=0?($yue['late_amount']-$data['real_amount']):0,
                        'deposit'=>($data['real_amount']-$yue['deposit'])>=0?0:($yue['deposit']-$data['real_amount'])
                    ];
                    M( "house", 'ware', C( 'DB_CONFIG2' ) )->where(['user_id'=>$data['user_id']])->save($up);
                    if($up['late_amount']===0){
                        $this->sub_model->where(  [ "pid" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 2 ] );
                        $this->user_model->where( [ 'id' => $data['user_id'] ] )->save( [ 'type_borr' => 1, 'renew' => 1 ] );//设置该用户的借款状态为，可借款，是否是续借设置为1（表示为续借）
                        $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 2 ] ); //将订单该订单的订单状态设置为已还款
                    }
                }
                //set_log( $data['id'], 1, 1, '人工审核还款 ' . $data['messgae'], '', '', $amountss + $yue['deposit'] );
                if(M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $add ))
                    $this->success( '审核成功！' );
                else
                    $this->error( '审核失败！' );
            }
            $ids = [];
            foreach($data['status'] as $k => $v) {
                $next = $k + 1;
                if(!isset( $data['status'][$next] )) {
                    $data['status'][$next] = 0;
                }
                //判断是否已超前还款（上一笔状态0或1必须>=下一笔还款状态）
                if($v >= $data['status'][$next]) {
                    if($v == 1) {
                        $ids[] = $k;//如果该笔为设置为已还款，则将这笔的order_sub的主键存起来
                    }
                } else {
                    $this->error( '不能超前还款！' );
                }
            }
            $where = [
                'pid' => $data['id'],
                'user_id' => $data['user_id'],
            ];
            $this->model->startTrans();
            //查询订单子分期记录（查未还款的记录）
            $order = $this->sub_model->where( 'status in (1,3,4) and id in (' . implode( ',', $ids ) . ')' )->where( $where )->select();
            $amounts = 0;
            $max_stages = 1;//用比较的方法在foreach中得到未还款记录里面的最大那期的分期数
            $stages = [];
            foreach($order as $k => $v) {
                $amounts += $v['amount'];//金额累加，累加出未还款的金额总和
                $st = substr( $v['stages'], 0, 1 );//拿到第一位数（分期的期数）
                $max_stages = $max_stages >= $st ? $max_stages : $st;//看至少要有一期，得到最大分期数
                $dt = [
                    'status' => 2,//将记录状态改为"已还款"
                ];
                $stages[] = $v['stages'];
                $wheres = [
                    'id' => $v['id'],
                    'pid' => $v['pid'],
                    'user_id' => $v['user_id'],
                ];
                $this->sub_model->where( $wheres )->save( $dt );//依次保存
            }
            //将用户申请还款(types=7)并且审核成功('status'=>1)的记录的金额总和查出来
            $logs = M( "log", 'system_', C( 'DB_CONFIG2' ))->where( [ 'user_id' => $data['id'], 'types' => 7, 'status' => 1 ] )
                ->where( 'stages in (' . implode( ',', $stages ) . ')' )->field( 'sum(amount) as amount' )->find();
            if(empty( $logs )) {
                $logs = 0;//如果没有，则金额为0
            } else {
                $logs = $logs['amount'];//如果有，则将用户还款的总金额拿出来
            }
            //账号余额
            $yue = M( "house", 'ware', C( 'DB_CONFIG2' ))->where( [ 'user_id' => $data['user_id'] ] )->find();
            if($result['stages'] == 1) {
                $type = 1;
            }else{
                //$sub=$this->sub_model->field('id')->where( 'status in (1,3,4)' )->where( $where )->find();
                $subs = $this->sub_model->field(['count(if(status=1,true,null))>0'=>'status_1','count(if(status=3,true,null))>0'=>'status_3','count(if(status=4,true,null))>0'=>'status_4'])->where( 'status in (1,3,4)' )->where( $where )->find();
                if($subs['status_3']){
                    $type=3;//逾期
                }elseif(!$subs['status_3'] && $subs['status_4']){
                    $type=2;//到期
                }elseif($subs['status_1'] && !$subs['status_3'] && !$subs['status_4']){
                    $type=0;//借款中
                }else{
                    $type=1;//还完了
                }
                //if(!empty($sub)){
                //    $type=0;
                //}else{
                //    $type=1;
                //}
            }
            //if($type) {
            //    $this->user_model->where( [ 'id' => $data['user_id'] ] )->save( [ 'type_borr' => 1, 'renew' => 1 ] );//设置该用户的借款状态为，可借款，是否是续借设置为1（表示为续借）
            //    $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 2 ] ); //将订单该订单的订单状态设置为已还款
            //} else {
            //    $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 1 ] );//将订单该订单的订单状态设置为借款中
            //}
           switch($type){
               case 0:
                   $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 1 ] );//将订单该订单的订单状态设置为借款中
                   break;
               case 1:
                   $this->user_model->where( [ 'id' => $data['user_id'] ] )->save( [ 'type_borr' => 1, 'renew' => 1 ] );//设置该用户的借款状态为，可借款，是否是续借设置为1（表示为续借）
                   $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 2 ] ); //将订单该订单的订单状态设置为已还款
                   break;
               case 2:
                   $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 4 ] );
                   break;
               case 3:
                   $this->model->where( [ "id" => $data['id'], 'user_id' => $data['user_id'] ] )->save( [ 'status' => 3 ] );
                   break;
           }

            //Todo:改用户余额
            $addA=[];
            //增加一个专门的三个实收
            $addA[] = [
                'user_id' => $data['id'],
                'examine_id' => get_current_admin_id(),
                'message' => '三个实收',
                'status' => 1,
                'types' => 4,
                'stages' => $result['stages'],
                'amount' => 0,
                'deposit' => 0,
                'wechat_amount'=>$data['wechat_amount'],
                'alipay_amount'=>$data['alipay_amount'],
                'bank_amount'=>$data['bank_amount'],
                'real_amount'=>$data['real_amount'],
                'overdue_amount'=>'',
                'payee'=>get_current_admin_id(),
            ];
            $admin_id=get_current_admin_id();
            $amountss = $amounts - $logs;//待还款总额-用户还款总额 = 待还款总额
            $user_yue=['deposit'=>0,'late_amount'=>($yue['late_amount']-$amountss)>0?($yue['late_amount']-$amountss):0];
            if($yue['deposit'] > 0) {//如果有余额，就充值
                $amountss = $amounts - $yue['deposit']- $logs;//待还款 - 余额
                if($amountss <=0) {//待还款比余额小，说明可以完全充满
                    $addA[] = [
                        'user_id' => $data['id'],
                        'examine_id' => 0,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 7,
                        'stages' => 1,
                        'amount' => $amounts- $logs,
                        'deposit' => 0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $addA[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 0,
                        'stages' => 1,
                        'amount' => $amounts- $logs,
                        //'deposit' => abs($amounts - $yue['deposit']- $logs),
                        'deposit' => abs( $yue['deposit']-($amounts - $logs)),
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    //$user_yue['deposit']=abs($amounts - $yue['deposit']- $logs);
                    $user_yue['deposit']=abs( $yue['deposit']-($amounts - $logs));
                } else if($amountss > 0) {
                    $addA[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '人工充值',
                        'status' => 1,
                        'types' => 0,
                        'stages' => 1,
                        'amount' => $amountss,
                        'deposit'=>0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $addA[] = [
                        'user_id' => $data['user_id'],
                        'examine_id' => $admin_id,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 0,
                        'stages' => 1,
                        'amount' => $amounts- $logs,
                        'deposit'=>0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                    $addA[] = [
                        'user_id' => $data['id'],
                        'examine_id' => 0,
                        'message' => '人工还款',
                        'status' => 1,
                        'types' => 7,
                        'stages' => $result['stages'],
                        'amount' => $yue['deposit'],
                        'deposit' => 0,
                        'wechat_amount' => '',
                        'alipay_amount' => '',
                        'bank_amount' => '',
                        'real_amount'=>'',
                        'overdue_amount'=>'',
                        'payee'=>get_current_admin_id(),
                    ];
                }
            }else{
                $addA[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工充值',
                    'status' => 1,
                    'types' => 0,
                    'stages' => 1,
                    'amount' => $amountss,
                    'deposit'=>0,
                    'wechat_amount' => '',
                    'alipay_amount' => '',
                    'bank_amount' => '',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
                $addA[] = [
                    'user_id' => $data['user_id'],
                    'examine_id' => $admin_id,
                    'message' => '人工还款',
                    'status' => 1,
                    'types' => 0,
                    'stages' => 1,
                    'amount' => $amounts- $logs,
                    'deposit'=>0,
                    'wechat_amount' => '',
                    'alipay_amount' => '',
                    'bank_amount' => '',
                    'real_amount'=>'',
                    'overdue_amount'=>'',
                    'payee'=>get_current_admin_id(),
                ];
            }
            M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->save($user_yue);
            //做记录
            $addA[] = [
                'user_id' => $data['id'],
                'examine_id' => $admin_id,
                'message' => '人工审核还款 ' . $data['messgae'],
                'status' => 1,
                'types' => 1,
                'stages' => 1,
                'amount' => $amountss>0?$amountss:0,
                'deposit'=>0,
                'wechat_amount' => '',
                'alipay_amount' => '',
                'bank_amount' => '',
                'real_amount'=>'',
                'overdue_amount'=>'',
                'payee'=>get_current_admin_id(),
            ];
            M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll($addA);
            $this->model->commit();//事务控制一下，略保险
            $url = $this->jum_url . "?app_act=index/wechat_r_f";
            $post_data = [
                'id' => $data['user_id'],
                'amount' => '',
                'type' => 3,
                'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['user_id'] ),
            ];
            A( 'indexlinks' )->http_post( $url, $post_data );
            //看display来判断后面跳转的路径，display为0的时候跳转到已到期列表，否则跳到未到期列表
            $url = I( 'get.display', 0 ) ? U( "Examine/loan_expire" ) : U( "Examine/loan_no_due" );
            $this->success( "审核成功！", $url );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 续期申请
     */
    function xu_list()
    {
        $where = [];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'c.name like "%' . $name . '%"';
        }
        if($name = I( 'request.order_id', 0 )) {
            $where[] = 'b.order_id like "%' . $name . '%"';
        }
        if($name = I( 'request.starts', 0 )) {
            $where[] = 'b.crtime >= "' . date( 'Y-m-d 00:00:00', strtotime( $name ) ) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] = 'b.crtime <= "' . date( 'Y-m-d 23:59:59', strtotime( $name ) ) . '"';
        }
        if($name = I( 'request.is_adult', 0 )) {
            if($name=='3'){
                $name=0;
            }
            $where[] = 'c.is_adult = "' . $name . '"';
        }
        $status = I( 'request.status' );
        if($status != '' && is_numeric( $status )) {
            $where[] = 'b.status=' . $status;
        }
        if($name = I('request.caiwu',0)){
            $ur = M( 'users' )->field( 'user_login' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = "'".$v['user_login']."'";
                }
                $where[] = 'd.loan_user in (' . implode( ',', $i ) . ')';
            }
        }
        $count = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) )
            ->join( "LEFT JOIN system_user c on c.id=b.user_id" )->join( "LEFT JOIN orders d on d.id=b.oid" )
            ->where( implode( ' and ', $where ) )->count();
        $page = $this->page( $count, 20 );
        $list = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) )
            ->join( "LEFT JOIN system_user c on c.id=b.user_id" )
            ->join( "LEFT JOIN orders d on d.id=b.oid" )
            //->join("LEFT JOIN system_log d on d.examine_id=b.lastuser_id and b.oid=d.user_id and d.message='人工审核续期 ' and d.types=3")
            ->where( implode( ' and ', $where ) )
            ->order( "b.crtime DESC,b.id desc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            //->field( 'c.name,c.mobile,c.identity,b.*,d.crtime as log_crtime' )
            ->field( 'd.loan_user,c.is_adult,c.name,c.mobile,c.identity,
            b.id,b.order_id,b.oid,b.user_id,b.amount,b.crtime,b.lastuser_id,b.renewal,b.endtime,b.status,b.stages' )
            ->select();
        //统计合计
        $for_total = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) )
            ->join( "LEFT JOIN system_user c on c.id=b.user_id" )
            ->join( "LEFT JOIN orders d on d.id=b.oid" )
            ->where( implode( ' and ', $where ) )
            ->field( 'sum(b.amount) as total_amount' )
            ->find();
        $this->assign($for_total);
        $ids = [];
        $oid=[];
        foreach($list as $v) {
            if(!empty($v['oid'])){
                $oid[]=$v['oid'];
            }
            if(empty( $v['lastuser_id'] )) {
                continue;
            }
            $ids[$v['lastuser_id']] = $v['lastuser_id'];
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /*
     * 审核续期 详情
     */
    function xu_info()
    {
        $id = I( 'get.id' );
        if(empty( $id )) {
            $this->error( '数据传入失败！' );
        }
        $info = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) )
            ->join( "LEFT JOIN system_user c on c.id=b.user_id" )
            ->join( "LEFT JOIN orders_sub d on d.pid=b.oid and b.stages=d.stages" )
            ->where( [ 'b.id' => $id ] )
            ->field( 'c.name,c.mobile,c.account_status,b.*,d.amount as order_amount,d.endtime as order_endtime' )
            ->find();
        $orther = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) )->where( [ 'oid' => $info['oid'] ] )->where( 'status>0' )->select();
        $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $info['oid'] . ' and types>0 and types<8' )->order( 'crtime desc' )->select();
        if(!empty( $log )) {
            $ids = [];
            foreach($log as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
                $ids[$v['payee']] = $v['payee'];//将收款人装起来
            }
            if(!empty( $ids )) {
                $users = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                $user = [];
                foreach($users as $v) {
                    $user[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $user );
            }
            $this->assign( 'log', $log );
        }
        $this->assign( 'order', $info );
        $this->assign( 'orther', $orther );
        $this->display();
    }

    /*
     * 续期审核 确认
     */
    function xu_act()
    {
        $type = I( 'get.display', 0 );
        $data = I( 'post.options' );
        if(empty( $data )) {
            $this->error( '数据传入失败！' );
        }
        $model = M( "renewal b", 'orders_', C( 'DB_CONFIG2' ) );
        $status = $model->where( [ 'id' => $data['id'], 'status' => 0 ] )->find();
        if(empty( $status )) {
            $this->error( '该续期已审核,请勿重复审核!', U( "Examine/xu_info" ) );
        }
        $st = $this->model->field( 'status,endtime,stages' )->where( [ 'user_id' => $status['user_id'], 'id' => $status['oid'] ] )->find();
        if($st['status'] == '2') {
            $this->error( '借款已还款,暂时不允许操作!' );
        }
        $examine_id = get_current_admin_id();
        $message_log = [];
        $update = [
            'status' => $type > 0 ? 1 : 2,
            'lastuser_id' => $examine_id,
            'message' => $data['messgae'],
        ];
        $model->where( [ 'id' => $data['id'], 'status' => 0 ] )->save( $update );
        $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $status['user_id'] ] )->find();
        if($type == 1) {//成功 改条子
            if($st['stages'] == 1){
                $num = 1;
            }else{
                $num = substr( $status['stages'], 0, 1 );
            }
            $message_log[] = [
                'user_id' => $status['user_id'],
                'examine_id' => $examine_id,
                'message' => $status['order_id'] . '续' . $num . '期成功',
                'status' => 1,
                'types' => 0,
                'amount' => 0,
                'stages' => $status['stages'],
                'deposit' => $yue['deposit'],
                'wechat_amount' => '',
                'alipay_amount' => '',
                'bank_amount' => '',
            ];
            $message_log[] = [
                'user_id' => $status['oid'],
                'examine_id' => 0,
                'message' => '人工审核续期 ' . $data['messgae'],
                'status' => 1,
                'types' => 3,
                'amount' => $status['amount'],
                'stages' => $status['stages'],
                'deposit' => 0,
                'wechat_amount' => '',/*$data['wechat_amount']*/
                'alipay_amount' => '',/*$data['alipay_amount']*/
                'bank_amount' => '',/*$data['bank_amount']*/
            ];
            $sub_order = $this->sub_model->where( [ 'user_id' => $status['user_id'], 'pid' => $status['oid'] ] )->where('status!=2')->field( 'id,endtime,stages,status' )->order( 'id asc' )->select();
            $stage = 2;
            $tis = false;
            $sta = 0;
            $endtime = $status['endtime'];
            foreach($sub_order as $vs) {
                $endtime = $endtime > $vs['endtime'] ? $endtime : $vs['endtime'];
                if($tis) {//取下一个子状态
                    if($sta!=3) {
                        $sta = $vs['status'];
                    } else {
                        $sta = 3;
                    }
                    $tis = false;
                }
                if($vs['stages'] == $status['stages']) {
                    if($st['stages'] == 1) {
                        $stage = $vs['stages'] + 1;
                    } else {
                        $num = substr( $vs['stages'], 1 );
                        if(empty( $num )) {
                            $num = 1;
                        } else {
                            $num += 1;
                        }
                        $stage = substr( $vs['stages'], 0, 1 ) . $num;
                    }
                    $tis = true;
                }
            }
            if($status['endtime'] == date( 'Y-m-d' )) {
                $sta_xu = 4;
            } else if($status['endtime'] < date( 'Y-m-d' )) {
                $sta_xu = 3;
            } else {
                $sta_xu = 1;
            }
            if(empty( $sta )) {
                $sta = $sta_xu;
            }
            if($sta_xu == 3 || $sta_xu == 4) {
                if($sta == 1) {
                    $sta = $sta_xu;
                }
                if($sta_xu == 3 && $sta==4){
                    $sta=3;
                }
            }
            $this->sub_model->where( [ 'user_id' => $status['user_id'], 'pid' => $status['oid'], 'stages' => $status['stages'] ] )->save( [ 'status' => $sta_xu, 'endtime' => $status['endtime'], 'stages' => $stage ] );
            $this->model->where( [ 'user_id' => $status['user_id'], 'id' => $status['oid'] ] )->save( [ 'status' => $sta, 'endtime' => $endtime ] );
            $url = $this->jum_url . "?app_act=index/wechat_r_f";
            $post_data = [
                'id' => $status['user_id'],
                'amount' => '',
                'type' => 4,
                'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $status['user_id'] ),
            ];
            A( 'indexlinks' )->http_post( $url, $post_data );
        } else {//退回余额
            $message_log[] = [
                'user_id' => $status['user_id'],
                'examine_id' => $examine_id,
                'message' => $status['order_id'] . '续期失败',
                'status' => 0,
                'types' => 0,
                'amount' => $status['amount'],
                'stages' => $status['stages'],
                'deposit' => $yue['deposit'] + $status['amount'],
                'wechat_amount' => '',
                'alipay_amount' => '',
                'bank_amount' => '',
            ];
            $message_log[] = [
                'user_id' => $status['oid'],
                'examine_id' => $examine_id,
                'message' => '人工审核续期 ' . $data['messgae'],
                'status' => 0,
                'types' => 3,
                'amount' => 0,
                'stages' => $status['stages'],
                'deposit' => 0,
                'wechat_amount' => '',
                'alipay_amount' => '',
                'bank_amount' => '',
            ];
            M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $status['user_id'] ] )->setInc( 'deposit', $status['amount'] );
        }
        M( "log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $message_log );
        $this->success( "审核成功！", U( "Examine/xu_list" ) );
    }

    public function loan_overdue_no()
    {
        $this->loan_no_due( 3, 'desc', false, 1 );
    }

    /*
     * 添加到不催缴
     */
    public function ban()
    {
        $id = I( 'get.id', 0 );
        $type = I( 'get.display', 0 );
        $third = I( 'get.third', 0 );
        if(!empty( $id ) && is_numeric( $id )) {
            if(!empty( $third )) {
                $result = $this->model->where( [ "id" => $id, "is_third" => 0 ] )->setField( 'is_third', 1 );
                if($result) {
                    $this->success( "加入到第三方催缴成功！" );
                } else {
                    $this->error( '加入到第三方催缴失败!' );
                }
            } else {
                $type = $type > 0 ? '1' : '0';
                $is_ban = $type > 0 ? '0' : '1';
                $result = $this->model->where( [ "id" => $id, "is_ban" => $type ] )->setField( 'is_ban', $is_ban );
                if($result) {
                    $this->success( "催缴设置成功！" );
                } else {
                    $this->error( '催缴设置失败!' );
                }
            }
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     *服务协议
     */
    public function fuwujkxy()
    {
        $id = I( 'get.id', 0 );
        if(empty( $id ) || !is_numeric( $id )) {
            $this->error( '数据传入失败！' );
        }
        $where = [
            'a.id=' . $id,
        ];
        $list = $this->model
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->where( implode( ' and ', $where ) )
            ->field( 'b.name,b.mobile,b.identity,a.*' )
            ->find();
        $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )
            ->field( 'crtime' )->where( [ 'user_id' => $list['id'], 'types' => '3' ] )
            ->order( 'crtime desc' )->find();
        if(!empty( $log )) {
            $list['loan_time'] = date( 'Y-m-d', strtotime( $log['crtime'] ) );
            $list['loan_day'] = (strtotime( $list['endtime'] ) - strtotime( $list['loan_time'] )) / (24 * 60 * 60);
        }
        $this->assign( "list", $list );
        $this->display( ':fuwujkxy' );
    }

    /*
     * 信用报告
     */
    function user_report()
    {
        $id = I( 'request.id', 0 );
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        //$id='10';
        $data = M( "report a", 'system_user_', C( 'DB_CONFIG2' ) )
            ->join( 'LEFT JOIN system_user b on b.id=a.user_id' )
            ->field( 'a.*,b.name' )
            ->where( [ 'a.user_id' => $id ] )->find();
        if(empty( $data )) {
            $url = $this->jum_url . "?app_act=index/report_r_f";
            $post_data = [
                'id' => $id,
                'sign' => md5( 'report报告' . md5( 'nuonuojinfu321' ) . $id ),
            ];
            $dt = A( 'indexlinks' )->http_post( $url, $post_data );
            $this->error( $dt['msg'] . ",请稍后重试！" );
        }
        $data['contact_region'] = A( 'report' )->_arr_sort( $data['contact_region'], 'region_call_out_cnt' );
        $data['contact_list'] = A( 'report' )->_arr_sort( $data['contact_list'], 'call_cnt' );
        //print_r($data['contact_list']);exit;
        $this->assign( 'list', $data );
        $this->display( ':user_report' );
    }

    /*
     * 电话号码导出
     */
    function mobile_down()
    {
        $id = I( 'request.id' );
        $url = "http://www.nuonuojinfu.cn/?app_act=index/daochu&";
        $post_data = [
            'sign=' . md5( '导出' . md5( 'nuonuojinfu321' ) . $id ),
            'user_id=' . $id,
            //'user_id=4519',
        ];
        redirect( $url . implode( '&', $post_data ) );
        //A('indexlinks')->http_get();
        exit;
    }

    /*
     * 贷后 批量认领
     */
    function bate_add()
    {
        $dt = I( 'post.id', 0 );
        $dis = I( 'request.display', 0 );
        switch ($dis){
            case '1':
                $str='byusers_loan';
                break;
            case 'M1':
                $str='byusers_loan_m1';
                break;
            case 'M2':
                $str='byusers_loan_m2';
                break;
            case 'M3':
                $str='byusers_loan_m3';
                break;
            default:
                $str='byusers';
        }
        $user = $this->user_model->where( 'id in (' . implode( ',', $dt ) . ')' )->where( [ $str => [ 'eq', 0 ] ] )->field( 'id' )->select();
        if(empty( $user )) {
            $this->error( "选择的用户已被认领！" );
        }
        $ids = [];
        foreach($user as $v) {
            $ids[] = $v['id'];
        }
        $this->user_model->where( 'id in (' . implode( ',', $ids ) . ')' )->save( [ $str => get_current_admin_id() ] );
        $this->success( "添加成功！" );
    }

    /*
     * 第三方催缴
     */
    function loan_third($type = '3', $desc = 'DESC', $byuser = true)
    {
        //判断是否是我已催缴列表
        $isLoanThirdUserList = false;
        '2' === $type && 'desc' === $desc && false === $byuser && ($isLoanThirdUserList = true);
        //判断是否是第三方催缴列表
        $isLoanThirdList = false;
        '3' === $type && 'DESC' === $desc && true === $byuser && ($isLoanThirdList = true);
        
        //判断是否需要合计
        $isNeedTotal = false;
        if($isLoanThirdUserList || $isLoanThirdList ){
            $isNeedTotal = true;
        }
        
        if($byuser) {
            $where = [
                'a.is_third=1',
            ];
        } else {
            $where = [
                'a.is_third=' . get_current_admin_id(),
            ];
        }
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts', 0 )) {
            $where[] = 'a.endtime >= "' . $name . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $where[] = 'a.endtime <= "' . $name . '"';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = 'a.loan_time >= "' . $name . '"';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = 'a.loan_time <= "' . $name . '"';
        }
        $where[] = 'a.status in (' . $type . ')';
        $other_where[]='d.id in (e.id)';
        $sql='SELECT count(a.id) as counts FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC ';
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $count=$this->model->query($sql);
        $page = $this->page( count($count), 20 );
        $sql='SELECT a.is_lock,b. NAME,b.mobile,b.account_status,b.identity,b.byusers_loan_m1,b.byusers_loan_m2,b.byusers_loan_m3,b.byusers,b.CODE,d.endtime AS sub_endtime,a.overdue_m_status,a.id,a.order_id,a.user_id,a. STATUS, a.amount, a.crtime, a.endtime,a.loan_day,a.loan_time, a.loan_amount, a.stages, a.lastuser_id,a.lastuser_name,a.loan_user FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d  GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC limit '.$page->firstRow . ',' . $page->listRows;

        $list=$this->model->query($sql);

        if($isNeedTotal){
            //统计合计
            $for_total = $this->model
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=" . $type )
                ->where( implode( ' and ', $where ) )
                ->field( 'a.amount' )
                ->group( 'a.order_id' )
                ->select();
            $for_total = [
                'total_amount'=>array_sum(array_column($for_total,'amount')),
            ];
            $this->assign($for_total);
        }

        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan'] )) {
                $ids[$v['byusers_loan']] = $v['byusers_loan'];
            }
            if(!empty( $v['byusers'] )) {
                $ids[$v['byusers']] = $v['byusers'];
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $codes = [];
        foreach($list as $v) {
        	if(!empty( $v['code'] )) {
        		$codes[$v['code']] = '"'.$v['code'].'"';
        	}
        }

        if(!empty( $codes )) {
        	$c = [];
        	$co = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->field( 'code,name' )->select();
        	foreach($co as $v) {
        		$c[$v['code']] = $v['name'];
        	}
        	$this->assign( 'codes', $c );
        }
        $this->assign( 'list', $list );
        $this->assign( 'type', $type );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    function loan_third_user()
    {
        $this->loan_third( '2', 'desc', false );
    }
    function other_finance(){
        $times = I( 'request.ends', 0 );
        if(empty($times)) {
            $times=date('Y-m-d H:i:s');
        }
        $where=[
            'a.crtime >="' . date('Y-m-d 00:00:00',strtotime($times)) . '"',
            'a.crtime <"' . date('Y-m-d 23:59:59',strtotime($times)) . '"',
            'a.status=1',
        ];
        if($name=I( 'request.name', 0 )) {
            $where[]='c.name like "%'.$name.'%"';
        }
        if($name = I('request.caiwu',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'a.examine_id in (' . implode( ',', $i ) . ')';
            }
        }
        //$where[] = 'b.status in (1,2,3,4)';
//        $count = $this->model->join( "LEFT JOIN system_user b on a.user_id=b.id" )->where( implode( ' and ', $where ) )->count();
//        $page = $this->page( $count, 20 );
        $select=[
            'a.crtime',
            'a.examine_id',
            'a.amount',
            'a.types',
            'a.message',
            'b.id',
            'b.order_id',
            'b.user_id',
            'c.`name`',
        ];
        switch (I( 'request.type', 0 )){
            case '1'://逾期
                $where[]='a.types=5';
                if(I( 'request.types', 0)){
                    $where[]='a.examine_id>0';
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.examine_id=0';
                }
                break;
            case '2'://续期
                $where[]='a.types=3';
                if(I( 'request.types', 0)){
                    $where[]='a.examine_id>0';
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.examine_id=0';
                }
                break;
            default:
                if(I( 'request.types', 0)){
                    $where[]='((a.types=1 and a.message like "人工审核还款%") or a.types=4)';
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.types=7';
                    $where[]='a.examine_id=0';
                }
        }
        $groupys='';
        $sql='select '.implode(',',$select).' from system_log a
        LEFT JOIN orders b ON a.user_id = b.id
        LEFT JOIN system_user c ON b.user_id = c.id
        where '.implode(' and ',$where).$groupys.' ORDER BY a.crtime desc';
        //print_r($sql);exit;
        $list=$data=M("log",'system_',C('DB_CONFIG2'))->query($sql);
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['examine_id'] )) {
                $ids[$v['examine_id']] = $v['examine_id'];
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $this->assign( 'list', $list );
        $this->display();
    }
    /*
     * 批量提额
     */
    function mention_amount(){
        $types=I('request.display',0);
        if(empty($types)){
            $list=M( "amount", 'system_', C( 'DB_CONFIG2' ) )->where(['status'=>1])->order('amount asc')->select();
            $this->assign( 'list', $list );
            $this->display();
        }else{
            $amount_id=I('request.amount_id',0);
            $ids=I('request.ids',0);
            if(empty($amount_id)){
                $this->error( "请选择正确的额度！" );
            }
            if(empty($ids)){
                $this->error( "请选择正确的用户！" );
            }
            $amount=M( "amount", 'system_', C( 'DB_CONFIG2' ) )->where(['id'=>$amount_id])->find();
            if(empty($amount)){
                $this->error( "所选的额度不存在!" );
            }
            $data=[];
            $ids=explode(',',$ids);
            $times=date('Y-m-d H:i:s');
            foreach($ids as $k=>$v){
                if(empty($v)){
                    unset($ids[$k]);
                    continue;
                }
                $data[]=[
                    'order_id'=>'JK'.substr(microtime(true) . rand(1, 10000), -4).substr(time(),2),
                    'user_id'=>$v,
                    'amount'=>$amount['amount'],
                    'endtime'=>date('Y-m-d',strtotime('+7 days')),
                    'loan_day'=>7,
                    'interest'=>$amount['interest'],
                    'examine'=>$amount['examine'],
                    'consulting'=>$amount['consulting'],
                    'modtime'=>$times,
                    'stages'=>'1',
                    'is_display'=>'0',
                    'renew'=>'1',
                    'loan_amount'=>$amount['amount'],
                ];
            }
            M( "ders", 'or', C( 'DB_CONFIG2' ) )->addAll($data);
            M( "house", 'ware', C( 'DB_CONFIG2' ) )->where('user_id in ('.implode(',',$ids).')')->save(['cash'=>$amount['amount']]);
            M( "user", 'system_', C( 'DB_CONFIG2' ) )->where('id in ('.implode(',',$ids).')')->save(['type_borr'=>4]);

            $user=M( "user", 'system_', C( 'DB_CONFIG2' ) )->field('mobile')->where('id in ('.implode(',',$ids).')')->select();
            if(empty($user)){
                $mobile=[];
                foreach($user as $v){
                    $mobile[]=$v['mobile'];
                }
//                $sms = new SmsLogModel();
//                $content='【诺诺信】你的审核已通过,额度3000,请在24小时内点击链接 http://t.cn/RY5SJN6 取款,过期自动取消,退订TD';
//                $sms->yx_send($mobile,$content);
            }
            //消息推送待定
            $url = $this->jum_url . "?app_act=index/wechat_r_f";
            $post_data = [
                'id' => $amount['amount'],
                'amount' => $times,
                'type' => 6,
                'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $amount['amount'] ),
            ];
            A( 'indexlinks' )->http_post( $url, $post_data );
            $this->success( "添加成功！" );
        }
    }
    /**
     * 逾期M1列表
     */
    function loan_overdue_user_m1()
    {
        $this->loan_overdue_usermnum(1);
        $this->display();
    }

    /**
     * 逾期M2列表
     */
    function loan_overdue_user_m2()
    {
        $this->loan_overdue_usermnum(2);
        $this->display();
    }

    /**
     * 逾期期数
     * @param $m_status M状态 例如:M1 1即为状态
     */
    public function loan_overdue_usermnum($m_status=1){
        $where = [
           // 'a.is_third = 0',
            'a.status = 3','d.status = 3','a.is_ban = 0'];
        if($name = I( 'request.name', 0 )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($name = I( 'request.mobile', 0 )) {
            $where[] = 'b.mobile like "%' . $name . '%"';
        }
        if($name = I( 'request.starts_r', 0 )) {
            $where[] = 'a.loan_time >= "' . $name . '"';
        }
        if($name = I( 'request.ends_r', 0 )) {
            $where[] = 'a.loan_time <= "' . $name . '"';
        }
        if($name = I( 'request.fengkong', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers in (0)';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.caiwu', 0 )) {
            $where[] = 'a.loan_user like "%' . $name . '%"';
        }
        if($name = I('request.daihou',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mone', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m1=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m1 in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mtwo', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m2=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m2 in (' . implode( ',', $i ) . ')';
            }
        }
        if($name = I( 'request.mthree', 0 )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(empty( $ur )) {
                $where[] = 'b.byusers_loan_m3=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'b.byusers_loan_m3 in (' . implode( ',', $i ) . ')';
            }
        }
        $byuser = I( 'request.byusers', 0 );
        if($byuser == 0) {
            $byuser = 3;
        }
        $group = get_groups_admin_user();
        switch($byuser) {
            case '1':
                $where[] = 'b.byusers_loan_m'.$m_status.'=0';
                break;
            case '3':
                if($group == 5) {
                    $where[] = 'b.byusers_loan_m'.$m_status.' in (0,' . get_current_admin_id() . ')';
                }
                break;
            default:
                $where[] = 'b.byusers_loan_m'.$m_status.' =' . get_current_admin_id();
        }
        $other_where=['a.overdue_m_status = '.$m_status];
        if($name = I( 'request.starts', 0 )) {//区分时间
            $other_where[] = 'd.endtime >= "' . date('Y-m-d',strtotime('-1days',strtotime($name))) . '"';
        }
        if($name = I( 'request.ends', 0 )) {
            $other_where[] = 'd.endtime <"' . $name . '"';
        }
        //合计
        $for_total = $this->model
            ->field( 'a.amount' )
            ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
            ->join( "LEFT JOIN orders_sub d on d.pid=a.id and d.status=3" )
            ->where( implode(' and ',array_merge_recursive($where,$other_where)) )
            ->group( 'a.order_id' )
            ->select();
        $other_where[]='d.id in (e.id)';
        //$sql='SELECT a.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id WHERE ('.implode( ' and ', $where ).') GROUP BY a.order_id ) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ';
        $sql='SELECT count(a.id) as counts FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC ';
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $count=$this->model->query($sql);
        $page = $this->page( count($count), 20 );
        $sql='SELECT a.is_lock,b.name,b.code,b.mobile,b.account_status,b.identity,b.byusers_loan_m1,b.byusers_loan_m2,b.byusers_loan_m3,b.byusers,b.CODE,d.endtime AS sub_endtime,a.overdue_m_status,a.id,a.order_id,a.user_id,a. STATUS, a.amount, a.crtime, a.endtime,a.loan_day,a.loan_time, a.loan_amount, a.stages, a.lastuser_id,a.lastuser_name,a.loan_user FROM orders a LEFT JOIN system_user b ON a.user_id = b.id LEFT JOIN orders_sub d ON d.pid = a.id,(SELECT d.id from (SELECT d.id,d.pid,d.endtime FROM orders_sub d LEFT JOIN orders a ON d.pid = a.id LEFT JOIN system_user b ON a.user_id = b.id WHERE ('.implode( ' and ', $where ).') ORDER BY d.endtime asc, a.loan_time DESC, d.id DESC) d  GROUP BY d.pid) e WHERE '.implode(' and ',$other_where).' GROUP BY a.order_id ORDER BY d.endtime DESC,a.loan_time DESC,a.id DESC limit '.$page->firstRow . ',' . $page->listRows;
//        if(get_current_admin_id()=='66'){
//            print_r($sql);exit;
//        }
        $list=$this->model->query($sql);
        $for_total = array(
            'total_amount'=>array_sum(array_column($for_total,'amount'))
        );
        $this->assign($for_total);
        $ids = [];
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['byusers_loan_m1'] ))
                $ids[$v['byusers_loan_m1']] = $v['byusers_loan_m1'];
            if(!empty( $v['byusers_loan_m2'] ))
                $ids[$v['byusers_loan_m2']] = $v['byusers_loan_m2'];
            if(!empty( $v['byusers_loan_m3'] ))
                $ids[$v['byusers_loan_m3']] = $v['byusers_loan_m3'];
            if(!empty( $v['byusers'] ))
                $ids[$v['byusers']] = $v['byusers'];
            if(!empty( $v['daihou_id'] ))
                $ids[$v['daihou_id']] = $v['daihou_id'];
            if(!empty( $v['code'] ))
                $codes[] = "'" . $v['code'] . "'";
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v)
                $u[$v['id']] = $v['user_login'];
            $this->assign( 'users', $u );
        }
        $shen_user = M( "users a" )->field('a.id,a.user_login')
            ->join('left join cmf_role_user b on b.user_id=a.id')
            ->join('left join cmf_role c on c.id=b.role_id')
            ->where( "c.name='M".$m_status."' and a.user_status=1" )
            ->order( 'a.id DESC' )->select();
        $this->assign( 'shen_user', $shen_user );
        //已加入黑名单的用户Id
        $b_where = 'user_type = 0 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>'.time().'))';
        $this->b_id_list = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->getField('user_id',true);
        if(!empty( $codes )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $is_ids );
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
    }

    /**
     * 电审记录
     */
    public function padtrial_record(){
        //$request_method = $_SERVER['REQUEST_METHOD'];
        $data = I( 'post.options', 0 );
        if(empty($data)){
            $pt_type = I('pt_type', 0);//0电审未审核列表 1续借电审列表
            $this->pt_type = $pt_type;
            $RoleUser = new RoleUser();
            $list = $RoleUser->getDaiHouList();
            //催收后记 这里等同于电审记录
            $cs_where['order_id'] = I('id');
            $this->cs_list = M('after_collection','system_',C('DB_CONFIG2'))->where($cs_where)->select();
            $this->assign('daihou',$list);
            $this->repayment( 2 );
        }else{
            if(empty( $data )) {
                $this->error( '数据传入失败！' );
            }
            $order_id = $data['id'];
            $admin_id = get_current_admin_id();//登录管理员ID
            $c_data['create_time'] = time();
            $c_data['createby'] = $admin_id;
            $c_data['collection_note'] = $data['collection_note'];
            $c_data['order_id'] = $order_id;
            $res = M( "after_collection", 'system_', C( 'DB_CONFIG2' ) )->add( $c_data );
            if($res){
                //$this->success( "添加催收记录成功！", U( "Examine/loan_overdue" ) );
                $this->success( "添加催收记录成功！<script>window.history.go(-1);</script>");
            }else{
                $this->error('添加催收记录失败');
            }
        }
    }
    /*
    * 锁定
    */
    function lock_morder(){
        $id=I( 'request.id', 0 );
        if(empty($id)){
            $this->error( "请选择正确的借款！" );
        }
        $result = M( "ders", 'or', C( 'DB_CONFIG2' ) )->where( [ "id" => $id, "status" => 3 ] )->save(['is_lock'=>'1'] );
        if($result) {
            $this->success( "借款锁定成功！");
        } else {
            $this->error( '锁定失败,请刷新重试！' );
        }
    }

    /**
     * 订单保证金列表
     */
    public function order_bond_list(){
        $where=[];
        //手机号码
        if($mobile = I( 'request.mobile', 0 )) {
            $where[] = 'u.mobile like "%' . $mobile . '%"';
        }
        //姓名
        if($name = I( 'request.name', 0 )) {
            $where[] = 'u.name like "%' . $name . '%"';
        }
        //是否成人
        $is_adult = I('request.is_adult', -1);
        if('-1'!=$is_adult){
            $where[] = 'u.is_adult =' .$is_adult. '';
        }
        //放款人（财务）
        if($loan_user = I('request.loan_user')){
            $where[] = 'o.loan_user LIKE "%'.$loan_user.'%"';
        }
        //创建日期 - 开始
        if($crtime_start = I('request.crtime_start')){
            $where[] = 'o.loan_time >= "'.$crtime_start.'"';
        }
        //创建日期 - 结束
        if($crtime_end = I('request.crtime_end')){
            $where[] = 'o.loan_time <= "'.$crtime_end.'"';
        }
        $count = M("order_bond ob", 'system_', C('DB_CONFIG2'))
            ->join("orders o on o.id = ob.order_id")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))->count();
        $page = $this->page( $count, 20 );
        $this->list = M("order_bond ob", 'system_', C('DB_CONFIG2'))
            ->field('o.id,o.order_id AS order_sn,o.loan_time,u.name,u.identity,o.amount,o.loan_day,o.stages,u.account_status,o.status,o.loan_user,
            ob.is_back,ob.bond_amount,u.is_adult,ob.is_deal,ob.op_record')
            ->join("orders o on o.id = ob.order_id")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))->order("o.loan_time DESC")
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign("page", $page->show('Admin'));

        //合计
        $for_total = M("order_bond ob", 'system_', C('DB_CONFIG2'))
            ->field('SUM(o.amount) AS total_amount,SUM(ob.bond_amount) AS total_bond_amount')
            ->join("orders o on o.id = ob.order_id")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))
            ->find();
        $this->assign($for_total);

        $this->display();
    }

    /**
     * 操作订单保证金
     */
    public function op_order_bond(){
        $order_id = I('id');
        if(IS_GET){
            $where['o.id'] = $order_id;
            $order = M("order_bond ob", 'system_', C('DB_CONFIG2'))
                ->field('o.id,ob.id AS ob_id,ob.user_id,o.order_id AS order_sn,o.crtime,u.name,u.identity,o.amount,o.loan_day,o.stages,
                u.account_status,o.status,ob.bond_amount,u.is_adult,u.mobile,u.silver_card,u.silver_number,o.interest,o.examine,o.consulting,o.loan_amount')
                ->join("orders o on o.id = ob.order_id")
                ->join("system_user u on u.id = o.user_id")
                ->where($where)
                ->find();
            //log
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $order['id'] . ' and types<8 and types>0 and types!=2' )->order( 'crtime desc' )->select();
            $logs = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( 'user_id=' . $order['user_id'] . ' and types=2' )->order( 'crtime desc' )->select();
            $ids = [];
            foreach($log as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            foreach($logs as $v) {
                if(empty( $v['examine_id'] )) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];
            }
            if(!empty( $ids )) {
                $users = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                $user = [];
                foreach($users as $v) {
                    $user[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $user );
            }
            $this->assign( 'order', $order );
            $this->assign( 'log', $log );
            $this->assign( 'logs', $logs );
            $this->display();
        }else{
            $options = $_POST['options'];
            $is_back = I('is_back');
            $op_record = I('op_record');
            $ob_id = $options['ob_id'];

            $where['id'] = $ob_id;

            $data['op_record'] = $op_record;
            $data['is_back'] = $is_back;
            $data['op_by'] = get_current_admin_id();
            $data['op_time'] = date('Y-m-d H:i:s');
            $data['is_deal'] = 1;
            $res = M('order_bond', 'system_', C('DB_CONFIG2'))
                ->where($where)->save($data);
            if($res){
                $this->success('操作成功',U('Examine/order_bond_list'));
            }else{
                $this->error('操作失败');
            }
        }
    }
    /*
     * 年中统计
     */
    function year_finance(){
        $start = I( 'request.start', 0 );
        $ends = I( 'request.ends', 0 );
        if(empty($ends)) {
            $ends=date('Y-m-d');
        }
        if(empty($start)) {
            $start=date('Y-m-d');
        }
        $where=[
            'a.crtime >"2018-02-12 10:30:00"',
            'a.crtime >="' . date('Y-m-d 00:00:00',strtotime($start)) . '"',
            'a.crtime <"' . date('Y-m-d 23:59:59',strtotime($ends)) . '"',
            'a.status=1',
        ];
        if($name=I( 'request.name', 0 )) {
            $where[]='c.name like "%'.$name.'%"';
        }
        if($name = I('request.caiwu',0)){
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                $where[] = 'a.examine_id in (' . implode( ',', $i ) . ')';
            }
        }
        //$where[] = 'b.status in (1,2,3,4)';
//        $count = $this->model->join( "LEFT JOIN system_user b on a.user_id=b.id" )->where( implode( ' and ', $where ) )->count();
//        $page = $this->page( $count, 20 );
        $select=[
            'a.crtime',
            'a.examine_id',
            'a.amount',
            'a.types',
            'a.message',
            'b.id',
            'b.order_id',
            'b.user_id',
            'c.`name`',
        ];
        switch (I( 'request.type', 0 )){
            case '1'://逾期
                $where[]='a.types=5';
                if(I( 'request.types', 0)==1){
                    $where[]='a.examine_id>0';
                    $where[]='a.message!="三个实收"';
                }else if(I( 'request.types', 0)==3){
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.examine_id=0';
                }
                break;
            case '2'://续期
                $where[]='a.types=3';
                if(I( 'request.types', 0)==1){
                    $where[]='a.examine_id>0';
                    $where[]='a.message!="三个实收"';
                }else if(I( 'request.types', 0)==3){
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.examine_id=0';
                }
                break;
            case '3':
                $where[]='((a.types in (3,4,5,7)) or (a.types=1 and a.message like "人工审核还款%"))';
                if(I( 'request.types', 0)==1){
                    $where[]='a.examine_id>0';
                    $where[]='a.message!="三个实收"';
                }else if(I( 'request.types', 0)==3){
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.examine_id=0';
                }
                break;
            default:
                if(I('request.types', 0)==1){
                    $where[]='((a.types=1 and a.message like "人工审核还款%") or a.types=4)';
                    $where[]='a.message!="三个实收"';
                }else if(I('request.types',0)=='3'){
                    $where[]='((a.types in (4,7)) or (a.types=1 and a.message like "人工审核还款%"))';
                    $where[]='a.message!="三个实收"';
                }else{
                    $where[]='a.types=7';
                    $where[]='a.examine_id=0';
                }
        }
        $groupys='';
        $sql='select '.implode(',',$select).' from system_log a
        LEFT JOIN orders b ON a.user_id = b.id
        LEFT JOIN system_user c ON b.user_id = c.id
        where '.implode(' and ',$where).$groupys.' ORDER BY a.crtime desc';
        //print_r($sql);exit;
        $list=$data=M("log",'system_',C('DB_CONFIG2'))->query($sql);
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['examine_id'] )) {
                $ids[$v['examine_id']] = $v['examine_id'];
            }
        }
        if(!empty( $ids )) {
            $u = [];
            $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            foreach($us as $v) {
                $u[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $u );
        }
        $this->assign( 'list', $list );
        $this->display();
    }


}
